C language - custom type 3

Consortium

Consortium definition

A union is a special custom type. The variables defined by this type also contain many members (types can be different), and the characteristic is that these members share the same memory space.
For example:

union My       //定义联合体类型
{
    
    
	char c;
	int i;
};
union My   un;    //定义联合体变量

int main()
{
    
    
	printf("%zd\n", sizeof(un));     //计算联合体变量大小
	return 0;
}

Commonwealth Features

The members of the union share the same memory space, that is, the size of the union is at least the size of the largest member.

union Un
{
    
    
	char a;
	int i;
}un;
int main()
{
    
    
	printf("%p\n", &(un.a));    //查看一下两个成员的地址
	printf("%p\n", &(un.i));

	return 0;
}

insert image description here
This also verifies that they all share the same memory space.

Calculation of Union Size

  • Union size is at least the size of the largest member
  • When the size of the largest member is not an integer multiple of the maximum alignment, it must be aligned to an integer multiple of the maximum alignment.
    For example:
union Un1
{
    
    
	char c[5];     //最大成员是5,最大对齐数是四,所以对齐到8
	int i;
};
union Un2
{
    
    
	short c[7];      //最大成员是14,最大对齐数是4,所以对齐到16
	int i;
};
int main()
{
    
    
	printf("%zd\n", sizeof(union Un1));
	printf("%zd\n", sizeof(union Un2));

	return 0;
}

insert image description here

Use Cases

int daxiao()
{
    
    
	union Un
	{
    
    
		char a;     //一个字节
		int i;      //四个字节
	}un;
	un.i = 1;
	return un.a;

}
int main()
{
    
    
	int ret = daxiao();
	if (ret)
		printf("小端");
	else
		printf("大端");
	return 0;
}

insert image description here
insert image description here
The first byte read is one for little-endian storage, and 0 for big-endian storage.

Guess you like

Origin blog.csdn.net/st200112266/article/details/127280522