无法初始化具有Union的Structs数组的元素

时间:2015-02-22 07:47:47

标签: 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

然后这就是我遇到的问题

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

当我尝试初始化人[1]时,我收到以下错误

  

错误:'{'标记

之前的预期表达式

我想知道这可能是什么原因?似乎我没有错过支撑,我也尝试去除内括号,但它仍然无法正常工作。任何帮助将非常感谢。谢谢

1 个答案:

答案 0 :(得分:4)

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

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引入了一个名称,以便我可以在初始化程序中引用它。

相关问题