Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast 32 bit int to 64 void * pointer without warning

I have a "generic" linked link in C that takes void * data to store the data in a Node.

insertNode(linkedList * list, void *data);

//Storing/retrieving a string works fine;
char *str="test"; 
insertNode(list, str);
char *getback=(char *)node->data;

//Storing/retrieving an Int results a cast warning
int num=1;
insertNode(list,(void *)num);
int getback=(int)node->data;

This is because int is 32 bit, but void * is 64 bit on x64 machine. What is the best practice to get rid of this error?

like image 204
Wei Shi Avatar asked Sep 12 '11 18:09

Wei Shi


People also ask

Can I cast a void * to an int?

Any expression can be cast to type void (which means that the result of the expression is ignored), but it's not legal to cast an expression of type void to type int — not least because the result of such a cast wouldn't make any sense.

What size is void * in 32 bit?

If the system is 32-bit, size of void pointer is 4 bytes. If the system is 64-bit, size of void pointer is 8 bytes.

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. The result need not be in the range of values of any integer type.

Can pointer be assigned to void?

void pointer in C / C++A void pointer is a pointer that has no associated data type with it. A void pointer can hold address of any type and can be typecasted to any type.


1 Answers

Use intptr_t or uintptr_t. They are integers of the same size as a pointer:

#include <stdint.h>
...
intptr_t num = 1;
insertNode(list, (void *) num);
intptr_t getback = (intptr_t) node->data;

Of course, the maximum value that you can store depends on the system, but you can examine it at compile time via INTPTR_MIN and INTPTR_MAX.

like image 186
Blagovest Buyukliev Avatar answered Sep 30 '22 04:09

Blagovest Buyukliev