如何使用{}声明指针结构?

Y_Y*_*Y_Y 4 c structure declaration

这可能是C编程语言中最简单的问题之一......

我有以下代码:

typedef struct node
{
  int data;
  struct node * after;
  struct node * before;
}node;

struct node head = {10,&head,&head};
Run Code Online (Sandbox Code Playgroud)

是否有一种方法可以使头部成为*头部[使其成为指针]并且仍然可以使用"{}"[{10,&head,&head}]来声明头部的实例并仍然将其留在全球范围?

例如:

 //not legal!!!
 struct node *head = {10,&head,&head};
Run Code Online (Sandbox Code Playgroud)

Tyl*_*ler 7

解决方案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);

}
Run Code Online (Sandbox Code Playgroud)

struct node *head = {10, head, head}因为没有为struct(int和两个指针)分配内存,所以一切都变得简单.

解决方案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);

}
Run Code Online (Sandbox Code Playgroud)

这将超出范围 - 解决方案1因此而优越,因为您正在创建链接列表,我相信您需要堆分配的内存 - 而不是堆栈分配.