Example 1:
<span style="font-size:18px;">#include <iostream>using namespace std;struct Node1{ bool m1; int m2;bool m3;double m4;bool m5;};// struct Node2{// char m1;// char m2;// int m3;// };int main(){cout << sizeof(Node1) << endl;/*cout << sizeof(Node2) << endl;*/}</span>
Output result: 32
Cause: Double (8)> int (4)> bool (1)
So Int Is used before the appearance of double. The memory allocation of each member variable of the original struct is: 1, 4, 1, 8, 1
Therefore, 1 extension to 4 and 4 remain unchanged, and the second 1 must be extended to 8, so that 1 (4) + 4 (4) + 1 (8) = 16 can be divisible by 8, the last 1 is extended to 8.
Total memory 4 + 4 + 8 + 8 + 8 = 32.
Example 2:
<span style="font-size:18px;">#include <iostream>using namespace std;struct Node1{ bool m1;bool m3; int m2;double m4;bool m5;};// struct Node2{// char m1;// char m2;// int m3;// };int main(){cout << sizeof(Node1) << endl;/*cout << sizeof(Node2) << endl;*/}</span>Output result: 24
Cause: see article 1
Example 3: Array
<span style="font-size:18px;">#include <iostream>using namespace std;// // struct Node1{// bool m1;// bool m3;// int m2;// double m4;// bool m5;// };struct Node2{ char m1; char m2[6];};int main(){/*cout << sizeof(Node1) << endl;*/cout << sizeof(Node2) << endl;}</span>
Result: 7
Cause: the char array cannot be regarded as an alignment, and node2 alignment is based on 1. Therefore, the result is 7;
Example 4: struct in struct
<span style="font-size:18px;">#include <iostream>using namespace std;struct Node1{ char m1; double m2;char m3;};struct Node2{char m1;Node1 m2;};int main(){/*cout << sizeof(Node1) << endl;*/cout << sizeof(Node2) << endl;}</span>
Output result: 32
Cause:
Node1 is 24. See example 1;
However, the alignment base in node1 is 8, because node2 only has char M1, and the base number is 1 less than the base number of node1 8;
Therefore, the alignment base of node1 is 8, but node1 is a whole. The content of the filled part cannot be allocated to M1 in node2. Hence
M1 must be allocated 8 bytes to him, total number of bytes; 8 + 24 = 32
Memory alignment Mode