[英]Initialize a struct in C using {}
In the marked line I get an error Error - expected expression
在标记的行中,我收到一个错误
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;
}
I know I can replace this line with我知道我可以用
p->blocked_list.node.next = &(p->blocked_list.node);
p->blocked_list.node.prev = &(p->blocked_list.node);
But can I make it work using {}
like I tried in the first piece of code?但是我可以像我在第一段代码中尝试的那样使用
{}
使其工作吗?
Initialization is allowed only when you define a variable.只有在定义变量时才允许初始化。 So, you can't use initializers in assignment.
所以,你不能在赋值中使用初始化器。 You can instead use C99's compound literals :
您可以改为使用 C99 的复合文字:
p->blocked_list.node = (struct list_head) {&(p->blocked_list.node), &(p->blocked_list.node)}; //error
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.