c - 初始化具有 Union 的 Struct 数组的元素时出现问题

标签 c arrays struct initialization unions

我在初始化也有 union 的结构时遇到问题。 我尝试遵循一些指南,看起来我的做法是正确的,但如果它不起作用,显然不是。

我有以下标题

#ifndef MENU_H_
#define MENU_H_

typedef struct student{
    int gpa;
    float tuitionFees;
    int numCourses;
}student;

typedef struct employee{
    float salary;
    int serviceYears;
    int level;
}employee;

typedef struct person{
    char firstName[20];
    char familyName[20];
    char telephoneNum[10];
    int type; // 0 = student / 1 = employee;
    union{
        employee e;
        student s;
    };
}newPerson;

#endif

这就是我遇到的麻烦

newPerson person[MAX_PERSONS];
person[1] = {"geo", "dude", "6136544565", 0, {3, 2353, 234}};

当我尝试初始化 person[1] 时,出现以下错误

error: expected expression before ‘{’ token

我想知道这可能是什么原因?似乎我没有缺少支架,我也尝试取下内部支架,但它仍然不起作用。任何帮助将非常感激。谢谢

最佳答案

错误消息涉及第一个左大括号。您可以使用大括号语法初始化对象,但不能分配它。换句话说,这是有效的:

int array[3] = {0, 8, 15};

但这不是:

array = {7, 8, 9};

C99 引入了复合文字,它看起来像是类型转换和初始化程序的组合,例如:

int *array;

array = (int[3]){ 1, 2, 3 };

C99 还引入了指定初始化,您可以在其中指定要初始化的数组索引或struct 或“union”字段:

int array[3] = {[2] = -1};        // {0, 0, -1}
employee e = {.level = 2};        // {0.0, 0, 3}

如果我们将这些功能应用于您的问题,我们会得到如下结果:

enum {
    STUDENT, EMPLOYEE
};

typedef struct student{
    int gpa;
    float tuitionFees;
    int numCourses;
} student;

typedef struct employee{
    float salary;
    int serviceYears;
    int level;
} employee;

typedef struct person{
    char firstName[20];
    char familyName[20];
    char telephoneNum[10];
    int type;
    union {
        employee e;
        student s;
    } data;
} person;

int main()
{
    person p[3];

    p[0] = (person) {
        "Alice", "Atkins", "555-0543", STUDENT,
        .data = { .s = { 20, 1234.50, 3 }}
    };

    p[1] = (person) {
        "Bob", "Burton", "555-8742", EMPLOYEE,
        .data = { .e = { 2000.15, 3, 2 }}
    };    

    return 0;
}

我为union引入了一个名称,以便我可以在初始化程序中引用它。

关于c - 初始化具有 Union 的 Struct 数组的元素时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28655680/

相关文章:

c - 指针、双指针、数组

c - Trie树并找到出现次数最多的n个单词,指针

c - 如何在结构的链表中搜索字符串以不仅首先找到所有出现的地方?

c - 初始化位域

python - Numpy 逐 block 减少操作

c - 为什么我在写入数组时遇到问题

c - poll() 在 macOS 上为超过 256 个描述符返回 EINVAL

c - 操作指针和函数

c - 尝试为 lex 程序创建 makefile

php - 如何将 <bars 转换为 (PHP 中的无序列表?