c - 在 C 中使用 {} 初始化结构体

标签 c struct initialization

在标记的行中,我收到错误错误 - 预期表达式

#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/

相关文章:

c - 为什么我的程序不会用 printf(); 显示每个元素?

python - 我什么时候应该在 LSTM 代码中初始化状态?

c - 初始化结构成员时出错

c - 修改 Code::Blocks 中的代码完成设置

c - 使用 getchar() 和 putchar() 将 int 与字符串交换

struct - Elixir:将字段作为另一种结构类型列表的 def 结构

matlab - 将结构数组的字段提取到新数组

c - 如何编写测试用例来验证 linux 中 sem_wait 函数返回的 EINTR

c - 如何在扩展 Guile 的 C 代码中将字符串转换为 bignum?

你能在 c 中运行初始化函数吗?