在标记行中,我得到一个错误Error - expected expression

#include <stdlib.h>

struct list_head {
    struct list_head *next, *prev;
};

struct program_struct {
    const char *name;
    struct list_head node;
};
typedef struct program_struct program_t;

struct task_t {
    program_t blocked_list;
};

int main() {

    struct task_t *p = malloc(sizeof(*p));
    p->blocked_list.name = NULL;
    p->blocked_list.node = {&(p->blocked_list.node), &(p->blocked_list.node)}; //error

    return 0;
}

我知道我可以用
p->blocked_list.node.next = &(p->blocked_list.node);
p->blocked_list.node.prev = &(p->blocked_list.node);

但我能像在第一段代码中那样使用{}来实现它吗?

最佳答案

只有在定义变量时才允许初始化所以,不能在赋值中使用初始值设定项。
您可以使用C99的compound literals

p->blocked_list.node = (struct list_head) {&(p->blocked_list.node), &(p->blocked_list.node)}; //error

关于c - 使用{}在C中初始化结构,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40038290/

10-11 23:02
查看更多