C语言 C 编程:将空指针转换为 int?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7828393/
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
C programming: casting a void pointer to an int?
提问by Tim
Say I have a void* named ptr. How exactly should I go about using ptr to store an int? Is it enough to write
假设我有一个名为 ptr 的 void*。我究竟应该如何使用 ptr 来存储 int?写够了吗
ptr = (void *)5;
If I want to save the number 5? Or do I have to malloc something to save it?
如果我想保存数字 5?或者我必须 malloc 一些东西来保存它?
回答by Brian Roach
You're casting 5to be a void pointerand assigning it to ptr.
您正在转换5为空指针并将其分配给ptr.
Now ptr points at the memory address 0x5
现在ptr 指向内存地址 0x5
If that actually is what you're trying to do .. well, yeah, that works. You ... probably don't want to do that.
如果这真的是你想要做的......好吧,是的,那行得通。你……可能不想那样做。
When you say "store an int" I'm going to guess you mean you want to actually store the integer value 5 in the memory pointed to by the void*. As long as there was enough memory allocated ( sizeof(int)) you could do so with casting ...
当你说“存储一个整数”时,我猜你的意思是你想将整数值 5 实际存储在void*. 只要分配了足够的内存 ( sizeof(int)),您就可以通过强制转换来实现...
void *ptr = malloc(sizeof(int));
*((int*)ptr) = 5;
printf("%d\n",*((int*)ptr));
回答by Boann
That will work on all platforms/environments where sizeof(void*) >= sizeof(int), which is probably most of them, but I think not all of them. You're not supposed to rely on it.
这将适用于所有平台/环境sizeof(void*) >= sizeof(int),这可能是其中的大部分,但我认为并非全部。你不应该依赖它。
If you can you should use a union instead:
如果可以,您应该改用联合:
union {
void *ptr;
int i;
};
Then you can be sure there's space to fit either type of data and you don't need a cast. (Just don't try to dereference the pointer while its got non-pointer data in it.)
然后,您可以确保有适合任何类型数据的空间,并且您不需要强制转换。(只是不要尝试在指针中有非指针数据时取消引用指针。)
Alternatively, if the reason you're doing this is that you were using an int to store an address, you should instead use size_tintptr_tso that that's big enough to hold any pointer value on any platform.
或者,如果您这样做的原因是您使用 int 来存储地址,则应改为使用它,以便它足够大以保存任何平台上的任何指针值。size_tintptr_t
回答by Jo.Manurung
A pointer always points to a memory address. So if you want to save a variable with pointer, what you wanna save in that pointer is the memory address of your variable.
指针始终指向内存地址。所以如果你想用指针保存一个变量,你想在那个指针中保存的是变量的内存地址。
回答by James
The castis sufficient..................
该cast是足够..................

