在结构中初始化结构?

Initializing a struct within a struct?

所以我有以下两个结构

typedef struct clienttable {
    vartable head;
    vartable tail;
} clienttable;

typedef struct vartable {
    int tableid;
    int randominfo;
    struct vartable *next;
} vartable;

我想像这样初始化它们。

clienttable *maintable;
maintable = (clienttable *) malloc (sizeof( clienttable));
maintable->head = {.tableid = 10, .randominfo=NULL, .next=NULL};

但是当我去编译时,我不断得到一个

expected expression before { token 

错误。我也试过 {10,NULL} 也无济于事。

我做错了什么?

此外,我是否需要 malloc clientable 和客户端 table 中的所有 table,或者只是 mallocing一个工作?

What am I doing wrong?

这个

maintable->head = ...

不是初始化而是赋值。

这个

... = {.tableid = 10, .randominfo=NULL, .next=NULL};

但是只能用于初始化。

所以把后者改成这个

... = (vartable) {.tableid = 10, .randominfo=0, .next=NULL};

使用复合文字的赋值。


... will I need to malloc both the clientable and all the tables within the client table, or will just mallocing the one work?

不太确定“所有表”指的是什么,但是通过分配 clienttable 类型的变量,您可以为其两个成员分配内存headtail。您没有headtail的成员next分配内存。