Let's say you have a node struct
, with the attribute, void* data
.
Is it possible to set the value of this pointer to some arbitrary integer value (ie, rather than doing something like node->data = &random_integer
).
I try the following lines:
NodePtr node = malloc(sizeof(Node));
*((int*)(node->data)) = 0;
This compiles without errors and warnings, but causes a segfault. I'm not exactly sure why.
I could easily set the void pointer to some &int
, but then I would have to allocate space for the &int
... and that seems unnecessary for such a simple operation.
This means you are trying to read from a memory location pointed to by node->data. In your code we don't see node->data being pointed to any memory location . First provide some memory to node->data using malloc.
Then try to access the value or write to it.