一、定义

  • 和结构体定义类似,只是把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;
}

C:20---联合/共用体(union)_联合

  • union是所有成员共同表示一个数据,如果更改了占位符,那么结果就会改变。例如:

printf("%c\t%c\t%d\n", p1.student, p1.teacher, p1.id);

C:20---联合/共用体(union)_数组_02



  • 成员的改变,一个改变全都改变

C:20---联合/共用体(union)_赋值_03


五、验证联合的成员指向与同一内存地址

  • 利用联合体证明内存的大小端​:​数值低位存储在内存的低地址,数值高位存储在内存的高地址



#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;
}

C:20---联合/共用体(union)_数组_04

  • 我们尝试更改一下arr的值

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;
}

C:20---联合/共用体(union)_union_05