2017-05-25 51 views
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; 
} 
+0

C不会阻止您访问与您分配的不同的联合成员,它只是未指定的行为。虽然两个结构都是一样的,但我认为它总是可以的。 – Barmar

+0

你预期会发生什么? –

+0

@ n.m。 ,匿名联合中只有一个结构(test1_struct或test2_struct)可以保存值,而另一个会打印垃圾 –

回答

0

联合指定两个成员将位于内存中的相同位置。因此,如果您分配给test1_struct,然后从test2_struct中读取,则它将解释test1_struct的内容,就好像它的格式为test2_struct

在这种情况下,两种结构都具有相同的格式,所以您读取和写入的内容没有区别。在两个成员相同的情况下使用联盟通常是没有意义的。联合的通常目的是拥有不同类型的成员,但不需要为每个成员分别存储内存,因为您一次只需要使用一种类型的内存。有关典型用例,请参阅How can a mixed data type (int, float, char, etc) be stored in an array?

请参阅Unions and type-punning了解访问与您分配的成员不同的成员的后果。