Alex Rivera | Logout

C programming: casting a void pointer to an int?

Asked 2011-10-19T21:28:49.590
25

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 save the number 5? Or do I have to malloc something to save it?

Edit
Report

1 Answer

7

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.

answered 2011-10-19T21:40:31.420

Your Answer