简体   繁体   中英

How can I declare a pointer structure using {}?

This probably is one of the easiest question ever in 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 I can make head to be *head [make it a pointer] and still have the availability to use '{ }' [{10,&head,&head}] to declare an instance of head and still leave it out in the global scope?

For example:

 //not legal!!!
 struct node *head = {10,&head,&head};

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);

}

Something as simple as struct node *head = {10, head, head} is not going to work because you haven't allocated the memory for the struct (the 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 will go out of scope - Solution 1 is superior for this reason and since you're creating a linked list, I believe you need heap allocated memory - not stack allocated.

You can make head a pointer, but you'll need to initialize it in a function.

struct node head_node;
struct node *head = &head_node;

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

There's no way you can initialize head ptr directly in global scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM