铸造一个指针为int [英] Casting a pointer to an int
问题描述
我写我自己的函数的malloc
和免费
C语言为一项任务。我需要的C SBRK()
包装函数的优势。据我了解 SBRK()
通过作为参数,指向程序中断的位置,传递的字节数递增程序的数据空间。
如果我有以下的code片断:
的#define BLOCK_SIZE 20
INT X;
X =(INT)SBRK(BLOCK_SIZE + 4);
我得到的编译器错误警告:从指针转换为大小不同的整数
。这是为什么,是有反正我可以通过 SBRK()
投指向的地址到 INT
?
我得到的编译器错误警告:一个指针转换为大小不同的整数结果。
这是为什么
块引用>由于指针和
INT
可能有不同的长度,例如,在64位系统中,的sizeof(无效*)
(即指针的长度),通常为8,但的sizeof(INT)
通常在此情况下,如果你投一个指向INT
丢回来,你会得到一个无效的指针,而不是原来的指针。
和有反正我可以SBRK()投下的地址指向一个int?
块引用>如果你真的需要一个指针转换为整数,你应该把它转换为一个
使用intptr_t
或uintptr_t形式
从< stdint.h方式>
从
< stdint.h>(P)
:
- 整数类型可容纳对象指针
以下类型表示与任何有效的指针作废可以转换为这种类型的属性有符号整数类型,则转换回指针作废,结果会比较等于原始指针:
使用intptr_t
以下类型表示与任何有效的指针作废可以转换为这种类型的属性的无符号整数类型,则转换回指针作废,结果会比较等于原始指针:
uintptr_t形式
在XSI兼容的系统中,
使用intptr_t
和uintptr_t形式
是必需的类型;否则,它们是可选的。
块引用>I am writing my own functions for
malloc
andfree
in C for an assignment. I need to take advantage of the Csbrk()
wrapper function. From what I understandsbrk()
increments the program's data space by the number of bytes passed as an argument and points to the location of the program break.If I have the following code snippet:
#define BLOCK_SIZE 20
int x;
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 bysbrk()
to anint
?解决方案I get the compiler error warning: cast from pointer to integer of different size.
Why is thisBecause pointer and
int
may have different length, for example, on 64-bit system,sizeof(void *)
(i.e. length of pointer) usually is 8, butsizeof(int)
usually is 4. In this case, if you cast a pointer to anint
and cast it back, you will get a invalid pointer instead of the original pointer.and is there anyway I can cast the address pointed to by sbrk() to an int?
If you really need to cast a pointer to an integer, you should cast it to an
intptr_t
oruintptr_t
, from<stdint.h>
.
From
<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_t
The 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_t
On XSI-conformant systems, the
intptr_t
anduintptr_t
types are required; otherwise, they are optional.
这篇关于铸造一个指针为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!