#include<stdio.h>
/*
* 联合(共用体):多个变量共用同一块内存空间,同一时间只能存在一个变量
* 使用union关键字定义联合
*
*/
//age sex
union What
{
int age; //4
char sex[6]; //6
short s; //2
};
struct Man
{
int type;
int dd;
};
struct WoMen
{
int type;
int x;
int m;
int c;
};
union Person
{
int type; //类型 0 女 1 男
struct Man man;
struct WoMen women;
};
int main()
{
struct Man m = { 1,20 };
struct WoMen wm = { 65,1,100 };
union Person per = { .women = wm };
if (per.type == 1)
{
struct Man tm = per.man;
printf("dd len:%d\n", tm.dd);
}
else
{
struct WoMen tm = per.women;
printf("x:%d m:%d c:%d\n", tm.x, tm.m, tm.c);
}
//初始化
union What w = { 18 };
//赋值的是哪个变量,就要访问哪个变量
//printf("%d\n", w.age);
printf("%s %d\n", w.sex, w.s);
printf("%d\n", sizeof(union What));
return 0;
}