one . structural morphology
structural morphology (struct) Is a data structure , Can contain many data types , It can realize more complex data structure .
common int,char Type variable , We can see at a glance how many bytes it takes , But for structures , But it's a little difficult .
Let's guess the output of the following program
struct S1 { char c1; int i; char c2; }; struct S2 { char c1; char c2; int i;
}; int main() { struct S1 s; struct S2 t; printf("%d\n", sizeof(s));
printf("%d\n", sizeof(t)); }
Maybe our answer is two 6, But is that the case ?
Not at all
original , There is memory alignment in the structure .
two . Structure memory alignment
Let's look at the alignment rules of structures :
1. The first member is offset from the structure variable by 0 Address of .
2. Other member variables to align to Alignment number At the address of an integer multiple of .
Alignment number : Compiler default alignment number and The structure member size Smaller value in
3. The total size of the structure is an integer multiple of the maximum number of alignments .
4. If there is a nested structure , The nested structure is aligned to its maximum integer multiple of its book , The overall size of the structure is an integral multiple of all the maximum alignments .
1. Size of non nested structure
Above ,c1 Place first ,i Size 4, take 4 and 8(VS Zhongmo thinks 8) Smaller value of , Align to 4
c2 Size 1, take 1 and 8 Smaller value of , Direct placement
Because the size of the structure is an integer multiple of its maximum number , Now the byte size is 9, So align to 12
( The cross is the wasted space )
In the figure above ,c1 and c2 Place first ,i Align to 8,8 by 4 Integer multiple of , Therefore, the output is 8
2. Size with nested structure
three . Why memory alignment
1. Platform reason ( Reasons for transplantation )
Not all hardware platforms can access any data on the address , Some hardware platforms can only access certain types of data at certain addresses , Otherwise, it will be abnormal .
2. Performance reasons
Ability to access memory at one time , Imagine , If memory is not aligned , It's hard to access an address with only half of the data .
Technology