gpt4 book ai didi

将指针转换为 int

转载 作者:行者123 更新时间:2023-12-05 01:24:55 25 4
gpt4 key购买 nike

我正在为 malloc 编写自己的函数和 free在 C 中进行分配。我需要利用 C sbrk()包装函数。据我了解sbrk()通过作为参数传递的字节数增加程序的数据空间并指向程序中断的位置。

如果我有以下代码片段:
#define BLOCK_SIZE 20int x;x = (int)sbrk(BLOCK_SIZE + 4);
我收到编译器错误 warning: cast from pointer to integer of different size .为什么会这样,无论如何我可以转换sbrk() 指向的地址到 int ?

最佳答案

I get the compiler error warning: cast from pointer to integer of different size.
Why is this


因为指针和 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?


如果您确实需要将指针强制转换为整数,则应该将其强制转换为 intptr_tuintptr_t ,来自 <stdint.h> .

来自 <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 and uintptr_t types are required; otherwise, they are optional.

关于将指针转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22624737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com