C语言 将指针转换为 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22624737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Casting a pointer to an int
提问by user3268401
I am writing my own functions for mallocand freein C for an assignment. I need to take advantage of the C sbrk()wrapper function. From what I understand sbrk()increments the program's data space by the number of bytes passed as an argument and points to the location of the program break.
我正在为一项任务编写自己的函数malloc和free在 C 中。我需要利用 Csbrk()包装函数。据我所知sbrk(),通过作为参数传递的字节数增加程序的数据空间并指向程序中断的位置。
If I have the following code snippet:
如果我有以下代码片段:
#define BLOCK_SIZE 20
#define BLOCK_SIZE 20
int x;
int x;
x = (int)sbrk(BLOCK_SIZE + 4);
x = (int)sbrk(BLOCK_SIZE + 4);
I get the compiler error warning: cast from pointer to integer of different size. Why is this and is there anyway I can cast the address pointed to by sbrk()to an int?
我收到编译器错误warning: cast from pointer to integer of different size。这是为什么,无论如何我可以将指向的地址sbrk()转换为int?
回答by Lee Duhem
I get the compiler error warning: cast from pointer to integer of different size.
Why is this
我收到编译器错误警告:从指针转换为不同大小的整数。
为什么是这样
Because pointer and intmay have different length, for example, on 64-bit system, sizeof(void *)(i.e. length of pointer) usually is 8, but sizeof(int)usually is 4. In this case, if you cast a pointer to an intand cast it back, you will get a invalid pointer instead of the original pointer.
因为指针和int可能具有不同的长度,例如,在64位的系统,sizeof(void *)(指针的长度即)通常为8,但sizeof(int)通常为4。在这种情况下,如果你施放的指针int和它转换回,你会获取无效指针而不是原始指针。
and is there anyway I can cast the address pointed to by sbrk() to an int?
无论如何我可以将 sbrk() 指向的地址转换为 int 吗?
If you really need to cast a pointer to an integer, you should cast it to an intptr_tor uintptr_t, from <stdint.h>.
如果您确实需要将指针转换为整数,则应将其转换为intptr_tor uintptr_t、 from <stdint.h>。
From <stdint.h>(P):
来自<stdint.h>(P):
- Integer types capable of holding object pointers
The following type designates a signed integer type with the property that any valid pointer to void can be converted to this type, then converted back to a pointer to void, and the result will compare equal to the original pointer:
intptr_tThe following type designates an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to a pointer to void, and the result will compare equal to the original pointer:
uintptr_tOn XSI-conformant systems, the
intptr_tanduintptr_ttypes are required; otherwise, they are optional.
- 能够保存对象指针的整数类型
以下类型指定一个有符号整数类型,其属性为任何指向 void 的有效指针都可以转换为该类型,然后转换回指向 void 的指针,并且结果将与原始指针相等:
intptr_t以下类型指定了一个无符号整数类型,其属性是任何指向 void 的有效指针都可以转换为该类型,然后转换回指向 void 的指针,并且结果将与原始指针相等:
uintptr_t在符合 XSI 的系统上,需要
intptr_t和uintptr_t类型;否则,它们是可选的。

