Solution 1:
#include <stdlib.h> #include <stdio.h> typedef struct node { int data; struct node * after; struct node * before; }node; int main() { struct node* head = (struct node *)malloc(sizeof(struct node)); //allocate memory *head = (struct node){10,head,head}; //cast to struct node printf("%d", head->data); }
Not as simple as struct node *head = {10, head, head} will not work, because you have not allocated memory for struct (int and two pointers).
Solution 2:
#include <stdlib.h> #include <stdio.h> typedef struct node { int data; struct node * after; struct node * before; }node; int main() { struct node* head = &(struct node){10,head,head}; printf("%d", head->data); }
This is beyond the scope. The solution for this reason is superior for this reason, and since you are creating a linked list, I believe that you need memory with a bunch, not a stack allocation.
source share