gpt4 book ai didi

c - 在c中访问 union 成员

转载 作者:太空狗 更新时间:2023-10-29 16:09:10 25 4
gpt4 key购买 nike

我有一个关于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?//我稍微修改了第一篇文章,因为它一开始就没有意义。

最佳答案

ISO/IEC 9899:1999(请参阅 the draft here)6.5.2.3 5 保证其有效:

One special guarantee is made in order to simplify the use of unions: if a union contains several structures that share a common initial sequence (see below), and if the union object currently contains one of these structures, it is permitted to inspect the common initial part of any of them anywhere that a declaration of the complete type of the union is visible. Two structures share a common initial sequence if corresponding members have compatible types (and, for bit-fields, the same widths) for a sequence of one or more initial members.

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com