c - C 中的结构初始化错误 : expected expression

标签 c

我有一个这样的结构:

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/

相关文章:

c++ - MPIR gcc 编译 - 找不到 -lmpir

c - ANSI C - 将数据从函数传递到 CHAR 指针

创建一个全局字符指针

c - 使用c更新文件中的记录

c - ARM 内联汇编代码在运行时无法正常工作

c - 扫描 radio 台

c - 用户输入的数组元素之和的问题

c - 我对位掩码感到困惑

c - Printf 打印不需要的换行符

C 程序没有正确读取参数