I need some help in working with Doubly Linked Lists, where the structure of a node contains a pointer to void. If I define another structure where I want to insert the actual data of a node, how do I assign it to the pointer to void? Also, how do I print the list?
Structure of my node, defined in a header file:
typedef struct nodetype
{
struct nodetype *prev, *next;
void *data;
} NodeT;
Structure of the data I want to insert in each node, defined in main.c:
typedef struct dataStructure
{
int birthday;
char *name;
}
You need to define the second typedef properly, e.g.
typedef struct dataStructure
{
int birthday;
char *name;
} dataStructure;
Then once you've allocated/defined the structures, you can set the pointer in the first type to the second as normal:
dataStructure mydatastruct;
node->data = &mydatastruct; //(void *) can point to anything
or
node->data = malloc(sizeof (dataStructure)); // direct allocation
You'll need to cast the void pointer to (dataStructure *)
if you want to access the members of the data structure via the node structure, e.g.
((dataStructure *)node->data)->birthday = 1980;
Macros can help make this less ugly.
If your node structure is only ever going to point to that data structure, it would be much simpler just to point to it directly, rather than use a void pointer.