初始化具有联合的结构数组的元素时遇到问题

use*_*517 2 c arrays struct initialization unions

我在初始化一个也有联合的结构时遇到了麻烦。我尝试遵循一些指南,似乎我是正确的,但如果它不起作用,显然不会。

我有以下标题

#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
Run Code Online (Sandbox Code Playgroud)

然后这就是我遇到的麻烦

newPerson person[MAX_PERSONS];
person[1] = {"geo", "dude", "6136544565", 0, {3, 2353, 234}};
Run Code Online (Sandbox Code Playgroud)

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

错误:'{' 标记前的预期表达式

我想知道这可能是什么原因?似乎我没有缺少大括号,我也尝试移除内部大括号,但它仍然不起作用。任何帮助将不胜感激。谢谢

M O*_*ehm 5

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

int array[3] = {0, 8, 15};
Run Code Online (Sandbox Code Playgroud)

但这不是:

array = {7, 8, 9};
Run Code Online (Sandbox Code Playgroud)

C99 引入了复合字面量,看起来像是类型转换和初始化器的组合,例如:

int *array;

array = (int[3]){ 1, 2, 3 };
Run Code Online (Sandbox Code Playgroud)

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

int array[3] = {[2] = -1};        // {0, 0, -1}
employee e = {.level = 2};        // {0.0, 0, 3}
Run Code Online (Sandbox Code Playgroud)

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

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;
}
Run Code Online (Sandbox Code Playgroud)

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