C programming: casting a void pointer to an int?

耗尽温柔 提交于 2019-12-02 20:35:50

You're casting 5 to be a void pointer and assigning it to ptr.

Now ptr points at the memory address 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 ...

void *ptr = malloc(sizeof(int));
*((int*)ptr) = 5;

printf("%d\n",*((int*)ptr));

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.

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_t intptr_t so that that's big enough to hold any pointer value on any platform.

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.

James

The cast is sufficient..................

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!