#include <stdio.h> //fopen函数的包
#include <stdlib.h> //exit()函数的包
#include <string.h>
//定义结构
struct Person{
char id;
int name [4];
double score;
};
//定义一个联合
union UPerson{
char id; //1
int name [2]; //4*4
double score; //8
};
//匿名联合
struct Owner{
char age;
double score;
//匿名联合
union { int uid; char *uname; };
//匿名结构
struct
{
int sid;
char *sname;
};
//int age;
};
int main()
{
//结构实例化
struct Person one =
{
.id='a',
.name={1, 2, 3, 4},
.score=1.987
};
//联合实例化
union UPerson uone;
union UPerson utwo = {.name = {6,8}};
//操作成员变量
uone.id = 'b';
uone.name[0] = 1;
uone.name[1] = 1;
uone.score = 19.88;
printf("uone.id=%c\n", uone.id );
printf("uone.name=%d======size:%zd\n", uone.name[0], sizeof(uone.name) );
printf("%f\n", uone.score );
printf("utwo-name:%d\n", *(utwo.name+1) );
printf("utwo-id:%d\n", utwo.id );
/*1.什么是联合Union
a.是一种数据类型,可以在内存中存储不同的数据类型(不是同时存储)
2.与结构的区别
a.union的大小由它的成员数据类型决定,确保能存储下最大成员变量的字节数
b.每次只能给union中的一个成员变量赋值
3.union就像一个可以存储多种类型的数据类型,每次为成员变量赋值都会把上次的值覆盖掉
*/
printf("查看结构的大小:%zd===id:%zd===name:%zd===score:%zd\n", sizeof(struct Person), sizeof(char), 4*sizeof(int), sizeof(double) );
printf("查看结构实例化的大小:%zd===id:%zd===name:%zd===score:%zd\n", sizeof(one), sizeof(one.id), sizeof(one.name), sizeof(one.score) );
printf("查看联合的大小:%zd\n", sizeof(union UPerson) );
printf("查看联合实例的大小:%zd\n", sizeof(uone) );
//匿名联合与匿名结构
//使用场景结构中成员为结构或者union时
struct Owner zhang =
{
.age = 'a',
.score = 18.88,
//.uid = 1,
.uname = "union",
.sid = 2,
.sname = "struct"
};
printf("匿名union中的uname:%s\n", zhang.uname );
printf("匿名struct中的uname:%s\n", zhang.sname );
return 0;
}