Sorry if the title is a little confusing, as a beginner to C I really didn't know how else to put it. So I'm trying to create a singly linkedlist where each node not only has a pointer to the next node, but also a pointer to sub-linkedlist that starts from that node. Basically each node has its own linkedlist. In trying to create this LL, I've got a struct that houses characteristics of what each node should have, such as a pointer to the next node and a pointer to the linkedlist of data that stems from it. I've heard that you're actually able to make a struct of a struct. I want to make a second struct that structures the types of data that the node is holding:
struct NODE{
void* data;
struct Node* next;
}NODE;
typedef struct stuff{
int data1;
int data2;
int data3;
}STUFF;
My question now, is that say I have a node from struct NODE like "NODE* node", how would I reference this node's types of data (data1, data2, etc)? I've tried casting, but not sure if I'm doing it wrong but something like this:
(STUFF)node->data1= DATA1;
//where DATA1 is of course already defined to be some int
I did this inside of a function, and I get the error "Assignment to cast is illegal, lvalue casts are not supported".
CodePudding user response:
Concerning your cast problem... Here is how you could do it.
typedef struct Node{
void* data;
struct Node* next;
}NODE;
typedef struct stuff{
int data1;
int data2;
int data3;
}STUFF;
int main()
{
NODE *n = malloc(sizeof(NODE));
n->data = malloc(sizeof(STUFF));
STUFF *s = n->data;
s->data1 = 15;
printf("%d", ((STUFF*) n->data)->data1);
return 0;
}