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?
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With