0
下面的代码提供了一个O/P: 101:name_provided:name_provided
匿名联合
AFAIK工会可以一次只持有一个成员,但它看起来像两个值是可见的,是正确的或者什么错代码。
#include <stdio.h>
struct test1{
char name[15];
};
struct test2{
char name[15];
};
struct data{
int num;
union{
struct test1 test1_struct;
struct test2 test2_struct;
};
};
int main()
{
struct data data_struct={101,"name_provided"};
printf("\n%d:%s:%s",data_struct.num,data_struct.test1_struct.name,data_struct.test2_struct.name);
return 0;
}
C不会阻止您访问与您分配的不同的联合成员,它只是未指定的行为。虽然两个结构都是一样的,但我认为它总是可以的。 – Barmar
你预期会发生什么? –
@ n.m。 ,匿名联合中只有一个结构(test1_struct或test2_struct)可以保存值,而另一个会打印垃圾 –