I haven't worked with linked lists in a long time, and I can't figure out why this code fails. I'm trying to create a very simple circular linked list with exactly 5 nodes. I will never need to insert additional nodes nor delete existing ones.
I get a 'node' has no member named 'next'
error. Can anyone tell me what I am doing wrong? Thanks.
typedef struct {
char payload[1024];
int x;
node* next;
} node;
node* root_ptr;
node this_node;
root_ptr = malloc(sizeof(node *));
root_ptr = &this_node; //keep a pointer to the root
int i;
for (i=0; i<5; i++) {
node next_node;
this_node.next = &next_node;
this_node = next_node;
}
this_node.next = root_ptr;
try this:
int main(){
// create root and helper nodes
node * root_ptr;
node * this_node = (node *)malloc(sizeof(node));
this_node->x = 0;
root_ptr = this_node; //keep a pointer to the root
int i;
// create list
for (i=1; i<5; i++) {
node * next_node = malloc(sizeof(node));
next_node->x = i;
this_node->next = next_node;
this_node = next_node;
}
// complete cycle
this_node->next = root_ptr;
this_node = root_ptr;
// check
for (i=0; i<5; i++){
printf("%d\n", this_node->x);
this_node=this_node->next;
}
return 0;
}
note that it's a generally bad idea to assign stack memory in a link list