Union (union)

1. United

联合是一种特殊的自定义类型,这种类型定义的变量也包含一系列的成员,
特征是这些成员公用同一块空间(所以联合也叫共用体)

2. Joint declaration and definition

//联合的声明
union Un
{
    
    
	int i;
	char c;
};
int main()
{
    
    
	//联合变量的定义
	union Un un;
	printf("%d\n", sizeof(un));
	un.i = 0x12345678;
	un.c = 0x00;
	return 0;
}

Insert picture description here

Insert picture description here
Debugging from the memory can see that two members share a memory space

3. Calculation of joint size

• 联合的大小至少是最大成员的大小
• 当最大成员大小不是最大对齐数的整数倍的时候,就要对齐到最大对齐数的整数倍

(1) Examples

#include<stdio.h>
union Un1
{
    
    
	char c[5];
	int i;
};
union Un2
{
    
    
	short c[7];
	int i;
};
int main()
{
    
    
	printf("%d\n", sizeof(union Un1));
	printf("%d\n", sizeof(union Un2));
}

In union Un1, char c[5] occupies 5 bytes, int i occupies 4 bytes, so the maximum member of the
union is 5, but the maximum alignment in union Un1 is 4, and 5 is not an integer multiple of the maximum alignment 4. , So you need to make up 3
bytes, the size of union Un1 is 8
in union Un2, short c[7] occupies 14 bytes, int i occupies 4 bytes, so the maximum member of the
union is 14, but the size of union Un2 The maximum alignment number is 4, 14 is not an integer multiple of the maximum alignment number 4, so 2
bytes need to be added , and the size of union Un2 is 16.
Insert picture description here

4. Use the joint to judge the large and small problems of the current machine

Utilize the feature of joint common memory

#include<stdio.h>
union Data
{
    
    
	int i;
	char ch;
};
int Judge()
{
    
    
	union Data A;
	A.i = 1;
	//小端机返回1,大端机返回0
	if (A.i = 1)
	{
    
    
		return 1;
	}
	else
	{
    
    
		return 0;
	}
}
int main()
{
    
    
	//大端机:数据低位放在内存高地址,高位放低地址
	//小端机:数据低位放在内存低地址,高位放高地址
	printf("%d\n", Judge());
	return 0;
}

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_50886514/article/details/112800300