C language learning: union union

  • Union is a type that can store different types of data in the same storage space.
  • The length of memory occupied by the union is equal to the length of its longest member.
  • The same memory segment can be used to store several different types of members, but only one function at a time.
  • The active member in the union variable is the last member stored, and the original member value will be overwritten after a new member is stored.
  • The address of the union variable and the addresses of its members are the same address.
union var
{
    
    
	double a;
	float b;
	int c;
	short d;
	char f;
}var;
int main()
{
    
    
	printf("%d\n",sizeof(var));
}
/*
	结果是8;符合联合体所占的内存长度等于其长度最长成员的长度
*/
union var
{
    
    
	double a;
	float b;
	int c;
	short d;
	char arr[12];
}var;
int main()
{
    
    
	printf("%d\n",sizeof(var));
}

/*
	结果是16;涉及内存对齐
	最长的数据类型是double,占8个字节,arr占了12个字节,但是要和double对齐,占用内存是8的倍数,也就是16.
*/

The similarities and differences between union and struct: Similarities:
Both can contain many data types and variables.
difference:

  • Structure: struct memory allocation is all allocated to you whether you use it or not.
  • Consortium: save memory
    for example :
#include <iostream>

using namespace std;


union vars
{
    
    
	double a;   //8
	float b;    //4
	int c;      //4
	short d;    //2
	char f[12]; //12
}var;


struct stus
{
    
    
    double a;    //8
	float b;     //4
	int c;       //4
	short d;     //2
	char f[12];  //12
}stu;

int main()
{
    
    
    printf("%d\n",sizeof(var)); //结果是16
    printf("%d\n",sizeof(stu)); //结果是32
    return 0;
}

The above picture is easy to understand.
Insert picture description here
For the union, first find the data type that occupies the largest byte in the union. Double occupies 8 bytes, and then find the member that occupies the largest space is arr, which occupies 12 bytes. If the space occupied is 8 Multiple, the result is 16.
Insert picture description here
For struct, the allocated memory size is greater than or equal to the sum of the memory occupied by the data members. Find out that the largest byte occupied by the data member in the structure is that the double occupies 8 bytes, the sum of the memory occupied by the structure is 30, the memory complement is a multiple of 8, and the final is 32.

ps: As for the alignment factor, each compiler on a specific platform has its own default "alignment factor", which can also be changed by the precompilation command #pragma pack(n), n=1,2,4,8,16 This coefficient, where n is the "alignment coefficient" you want to specify.
Leave the hole first, and write a detailed discussion later.

Guess you like

Origin blog.csdn.net/Yang_1998/article/details/106480231