I am writing a program that implements a stack in c. I want each node to take any type of data(ie int char struct etc) if I declare my node struct as
typedef struct node{
void *data;
struct node *next;
}Node;
Does that allow my void pointer data to point to any type of memory?
Yes, but there are some caveats involving dereferencing your void pointer to access the data inside.
Basically, say you have a node:
And you have some Point structure:
And you put a point in a node:
In order to access the members of the point, you have to use a typecast:
Or you can assign a pointer of the correct type and copy the void pointer:
Because this won’t work:
That’s because a void pointer contains no type information for the compiler to make sense of what’s being pointed to by a void pointer.
And that’s pretty much all you need to know about how to use void pointers.