我有一个这样的结构:
struct foobar {
int i;
char *word;
};
我知道这会起作用:
struct foobar {
int i;
char *word;
};
struct foobar three = {3, "three"};
为什么下面的方法不起作用?
struct foobar {
int i;
char *word;
} three;
three = {3, "three"};
它会给出错误:expected expression before ‘{’ token
。
最佳答案
它不起作用,因为 C 不知道 {3, "three"} 应该是什么类型; C 不会查看“=”运算符的左侧来猜测您的类型,因此您在那里没有任何类型信息。对于 C99,您可以为此使用复合文字:
three = (struct foobar) { 3, "three" };
强制转换给出了类型,大括号中的值是初始值设定项。然后将结果分配给您的变量三。
关于c - C 中的结构初始化错误 : expected expression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43643041/