1. 联合体的定义
联合体是成员共用内存空间。
用法与struct
一样。不同点是所有成员公用相同的内存空间。联合体的sizeof
是成员中大小最大的值。
写法: union 类型名 u;
union 联合体类型名 {
成员
};
2.案例
example1
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
union Test{
int n;
double b;
};
void main()
{
printf("%ld\n",sizeof(union Test)); //8
union Test u;
u.b = 0;
u.n = 0;
printf("u.n=%d u.b=%f\n",u.n,u.b); //0 0
u.b = M_PI;
printf("u.n=%d u.b=%f\n",u.n,u.b);
}
8
u.n=0 u.b=0.000000
u.n=1413754136 u.b=3.141593
example2
:如何判断大小端
int IsSmallEnd1()
{
union U u;
u.a = 0x11223344;
if (u.c == 0x44)
{
return 1;
}
else
return 0;
}
int main()
{
int i = IsSmallEnd1();
if (i == 1)
{
printf("小端模式\n");
}
else
{
printf("大端模式\n");
}
return 0;
}
example3
:
按从低到高的顺序打印出int类型每个字节的对应的数值(十六进制)。请绘制出数据布局图。
小端
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
union IntByte{
int n;
char c[sizeof(int)];
};
void main()
{
union IntByte b;
b.n = 1234;
int i;
printf("%08X\n",b.n);
for(i=0;i<sizeof(int);++i){
printf("%p\t%02hhX",b.c+i,b.c[i]);
}
printf("\n");
}