Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C programming: casting a void pointer to an int?

Tags:

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?

like image 342
Tim Avatar asked Oct 19 '11 21:10

Tim


People also ask

How do I cast a void pointer to integer?

After declaration, we store the address of variable 'data' in a void pointer variable, i.e., ptr. Now, we want to assign the void pointer to integer pointer, in order to do this, we need to apply the cast operator, i.e., (int *) to the void pointer variable.

Can you cast a pointer to an int?

Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined.

What does casting to void do in C?

Casting to void is used to suppress compiler warnings. The Standard says in §5.2. 9/4 says, Any expression can be explicitly converted to type “cv void.” The expression value is discarded. Follow this answer to receive notifications.

Can void pointer point to any type?

The pointer to void can be used in generic functions in C because it is capable of pointing to any data type. One can assign the void pointer with any data type's address, and then assign the void pointer to any pointer without even performing some sort of explicit typecasting.


2 Answers

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.

like image 41
Boann Avatar answered Oct 20 '22 15:10

Boann


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)); 
like image 165
Brian Roach Avatar answered Oct 20 '22 17:10

Brian Roach