c - 如何在 C 中访问 union 内的结构成员?

标签 c unions structure

我有以下 union :

union employee
{
    char key;

    struct manager
    {
        short int age;
        float shares;
        short int level;
    };

    struct worker
    {
        short int age;
        short int skill;
        short int department;
    };

} company[10];

如何访问 union employee 中的结构成员? 我试图以这种方式访问​​ manager 结构的 age 成员:

公司[i].manager.age

但我收到error C2039: 'manager' : is not member of 'employee'

最佳答案

在标签声明之后添加一些东西。也许:

struct manager
{
    short int age;
    float shares;
    short int level;
} manager;

旁注:您没有使用 union 权利。关键,即告诉您是与经理打交道还是与普通 worker 打交道的字段,应该在封闭对象中,在 union 之外。也许:

struct employee {
    char key;

    union {
        struct manager ...;
        struct worker ...;
    } u;
};

作为dasblinkenlight请注意,您可以在 union 外声明您的经理/ worker 标签。

关于c - 如何在 C 中访问 union 内的结构成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12653500/

相关文章:

c - 使用分隔符分隔字符串和整数

C++ mktime 更改我的 tm_struct 的值

c - 在 C 中提取 16 位 union 中的位位置

c++ - c\c++ - 以 union 作为参数以满足特定要求的函数

c - 访问嵌套结构变量

c - 为结构指针分配内存

无法从c中的堆栈结构复制字符串

c - 使用 OpenMP 时 snprintf 中的段错误

c - sscanf 有什么问题?

c - 初始化 union 类型的二维数组(整数或字符)