How can I declare a pointer structure using {}?

This is probably one of the simplest questions in the C programming language ...

I have the following code:

typedef struct node { int data; struct node * after; struct node * before; }node; struct node head = {10,&head,&head}; 

Is there a way to make the head be * head [make it a pointer] and still have accessibility to use '{}' [{10, & head, & head}] to declare an instance of the head and still leave it globally?

For instance:

  //not legal!!! struct node *head = {10,&head,&head}; 
+4
source share
2 answers

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.

+7
source

You can make the header a pointer, but you will need to initialize it in a function.

 struct node head_node; struct node *head = &head_node; void initialize() { *head = {10,&head_node,&head_node}; } 

It is not possible to initialize head ptr directly in the global scope.

0
source

Source: https://habr.com/ru/post/1308099/


All Articles