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 *)5;
If I want to sav
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.