C:20---联合/共用体(union)
时间 2021-01-03
标签
联合
共用体
union
一、定义
- 和结构体定义类似,只是把struct改为union
- 联合也可以使用typedef取别名
union person
{
char student;
char teacher;
int id;
};
typedef union person
{
char student;
char teacher;
int id;
}person,*p_person;
二、联合的特点
- 无论联合体内有多少成员,联合体的大小始终都是最大数据类型的大小
- 在同一时间点,联合只能存储一个值,并且所有的成员使用的都是这个存储的值
- 联合的所有成员指向于在同一内存空间中:如果一个改变所有都改变,但不能同时存储
- 联合的一个用法:设计一种表以存储即无规律,事先又不知道顺序的混合类型
三、联合数组
- 功能:联合数组中的每个联合大小相等,可以存储各种数据类型
四、演示案例
typedef union person
{
char student;
char teacher;
int id;
}person;
printf("%d\n",sizeof(person));//4字节
typedef union person
{
char student;
char teacher;
int id;
}person;
int main()
{
person p1;
p1.student='c';//给一个赋值,其他成员都使用这个值
printf("%c\t%c\t%c\n",p1.student,p1.teacher,p1.id);
return 0;
}
五、验证联合的成员指向与同一内存地址
- 利用联合体证明内存的大小端:数值低位存储在内存的低地址,数值高位存储在内存的高地址
#include<stdio.h>
#include<string.h>
typedef union temp
{
char arr[4];
int num;
}temp;
int main()
{
temp p;
p.num=0x12345678;
for(int i=0;i<4;++i)
printf("0x%x\t",p.arr[i]);
printf("\n");
return 0;
}
typedef union temp
{
char arr[4];
int num;
}temp;
int main()
{
temp p;
p.num=0x12345678;
for(int i=0;i<4;++i)
printf("0x%x\t",p.arr[i]);
p.arr[1]=0x00;//更改第2个字节的值为0
printf("\n");
for(int j=0;j<4;++j)
printf("0x%x\t",p.arr[j]);
printf("\n");
return 0;
}