我有一个关于c语言 union 的问题

例如:

typedef struct {
    int a;
     float c;
}Type1;


typedef struct {
    int b;
     char d;
}Type2;

union Select {
    Type1 type1;
    Type2 type2;
};


void main() {
    Select* select;
    //can we access type1 first and then access type2 immediately? like this way:
    select->type1.a;
    select->type2.b;

//访问type1后,立即访问type2,能得到type2的值b吗?
//我对第一篇文章做了一点修改,因为开头毫无意义。

}

最佳答案

对,那是正确的。在您的示例中(忽略未初始化的指针),对于任何给定的 type1.a 实例, type2.bSelect 的值将始终相同。

关于c - 在 c 中访问 union 成员,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7663624/

10-11 16:48