First, we introduce two concepts: "data type size" and "specify alignment value ":
Data type size: char is 1 byte, short is 2 bytes, int Is 4 bytes, double is 8 bytes, and so on;
Specify alignment value: # alignment value specified by pragma pack (value). For example, the default value of g ++ 4.5.2 x86 is 4;
Introduce an important concept-effective alignment value N:
Valid alignment value N = min (1), (2), that is, the minimum value of "data type size" and "specified alignment value.
In C/C ++, the following conditions A and B must be met simultaneously:
Condition A: The starting address of the data member of the struct (struct), addr_start, must be an integer multiple of the valid alignment value N, that is, addr_start % N = 0;
Condition B: the size of the struct (struct) must be an integer multiple of max_N, that is, sizeof (struct) % max_N = 0.
For example:
Struct {
Char a1;
Short a2;
Short a3;
Double a4;
Int a5;
Char a6;
};
The alignment value specified by the author's machine is 4 by default. Analysis:
The valid alignment value of a1 is 1, and the starting address is 0, which occupies 1 byte;
The valid alignment value of a2 is 2. Due to Condition A, the starting address is 2. There is no 1 byte between a1 and a2, and a2 occupies 2 bytes;
The valid alignment value of a3 is 2. The starting address of Condition A is 4 and there is no interval. a3 occupies 2 bytes;
The valid alignment value of a4 is 4. Because of Condition A, the starting address is 8 and there is no interval. a4 occupies 8 bytes;
The valid alignment value of a5 is 4. Because of Condition A, the starting address is 12 and there is no interval. a4 occupies 4 bytes;
The valid alignment value of a6 is 1. Because of Condition A, the starting address is 15 and there is no interval. a5 occupies 1 byte;
Given Condition B, the maximum valid alignment value is 4 and the total length is a multiple of 4. The final complement of the struct is 3 bytes.
Therefore, the total size of the above struct is 24 bytes.
From: Technical column of Yang zhuocheng