joint
Union is a special custom type. The variables defined by this type also contain a series of members. The characteristic is that these members share the same space, so it is also called a union.
Calculation of joint size
-
The size of the union is at least the size of the largest member, so as to be able to save the largest member.
-
When the maximum member size is not an integral multiple of the maximum alignment, it must be aligned to an integral multiple of the maximum alignment.
#include <stdio.h> //联合的声明 union Un { short s[7]; int n; }; int main() { //联合的定义 union Un un; //计算联合的大小 printf("%d\n", sizeof(union Un));//16 printf("%d\n", sizeof(un));//16 return 0; }
Because my computer has 32 data buses, the maximum alignment number of my computer is 4. We find the largest member short s[7] in the union, which requires 14 bytes, and then fill it up to the maximum alignment number 4. Integer multiples, the result is 16.
Use joint judgment of the computer
//大端返回1,小端返回0,要求借用联合体的特性
union Data
{
int i;
char ch;
};
int isBigSystem()
{
union Data d;
//d.i = 0x00000001;
d.i = 1;
if (d.ch == 1)
{
return 0;
}
else
{
return 1;
}
}
//小端机低位放低位,高位放高位,小端机
//大端机低位放高位,高位放低位,大端机
int main()
{
printf("%d\n", isBigSystem());
return 0;
}