Setting a void pointer's value to an integer

1.9k views Asked by At

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.

1

There are 1 answers

2
Gopi On BEST ANSWER
*(node->data)

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.

node->data = malloc(sizeof(int));

Then try to access the value or write to it.

*((int *)(node->data)) = 1; /* or any value */