eg
struct node{ char c ; int x;};
After you define this node, the memory allocated by the system is not simply the sizeof (char) +sizeof (int) = 5, but the memory alignment method.
First, in the computer, there will be a default parameter, that is, the number of aligned film, the general default is 8 bytes, but you can change its value by adding the following command in the program
#pragma pack (n);
Once you know the number of Zimo, you can begin to say the rules of alignment.
1: When the system allocates memory to it, it is the principle that you define successively, for example, above node defines char first, then defines int, then the system assigns the memory to Char first, then assigns the INT
2: After the system allocates space for the first defined type, and then assigns the second type, its offset from the starting position of the struct must be an integer multiple of min (for Zimo number, byte size of this type),
For example, to allocate memory to node, the alignment parameter is 2, at the starting position 0x00 assigns a 1byte space to char, and then assigns an int, the memory starting position of type int is the integer multiple of min (2,4), the minimum is 2,
Therefore, the starting position of the int is 0x02, if the alignment parameter is 4, then the starting position of 0x04 can be calculated;
3: After allocating space for all types, the total space of the struct is an integer multiple of min (for Zimo, the largest byte in the struct),
eg
#pragma pack (8); struct node{ Double x;
char c;};
In front of the two principles, double memory starting position is 0x00, char starting position is 0x09, so the total space is 9byte, but because there is a third rule, the total space must be min (sizeof (double), 8) of the integer times, so the total space is 16 bytes.
2union when allocating memory, its total space is an integer multiple of min (for Zimo, the largest type of byte in the Union), and the total space must be the maximum space defined in >=union.
eg
#pragma pack (8); typedef union{ char c[]; int x;} U;
Min (8, sizeof (int)) = 4, so the optional total space value is 4, 8, 12, ..... , but since you have defined a char array with a size of 10, you need 10byte, so 4 and 8 are too small, so the total space is 12.
Memory allocations for structs and unions