How to determine the memory alignment rules, sizeof results, please keep in mind the following 3 principles: (In the absence of #pragma pack macros, be sure to read the last line)
1: Data member Alignment rule: A data member of a struct (struct) (or union) whose first data member is placed at 0, where each data member is stored starting from the size of the member or the member's child member, as long as the member has a child member, such as an array, structure, etc.), starting at an integer multiple (for example, int in the 32-bit machine is 4 bytes), starting at the integer multiple address of 4.
2: A struct is a member: If a struct has certain members of the structure, the member of the struct body is to be stored from the integer multiple address of its internal maximum element size. (in struct a There are char,int, double, etc. in struct b,b, which should be stored as an integral number of 8.)
3: Finishing work: The total size of the structure, that is, the result of the sizeof,. Must be an integer multiple of the largest member within it. The insufficiency must be filled.
After you read this 3 principles, 2 minutes have passed, seize the time, combat 3 minutes:
typedef struct BB
{
int id; [0] ..... [3]
Double weight; [8] ... [15] Principle 1
float height; [16]. [19], total length to be 8 integral times, padded [20] ... [23] Principle 3
}BB;
typedef struct AA
{
Char name[2]; [0],[1]
int id; [4]. [7] Principle 1
Double score; [8] ..... [15]
Short grade; [16],[17]
BB b; [24] ... [47] Principle 2
}AA;
int main ()
{
AA A;
Cout<<sizeof (a) << "" <<sizeof (BB) <<endl;
return 0;
}
The result is
48 24
OK, the above all see understand, memory alignment basic clearance.
Tell me more about #pragma pack ().
Add a #pragma pack (1) before the code, and you'll be glad to see that the code above is output to
32 16
BB is 4+8+4=16,aa is 2+4+8+2+16=32;
Is this not the ideal world with no memory alignment? Yes, #pragma pack (1) tells the compiler that all alignments are aligned according to the integer multiples of 1, in other words, there is no alignment rule.
Do you understand me?
What about the results of the #pragma pack (2)? I'm sorry, it's 5 minutes.
The Ps:vc,vs compiler defaults to the #pragma pack (8), so testing our rules is normal; note that GCC defaults to #pragma pack (4), and GCC only supports 1,2,4 alignment. The alignment value computed in the three principles is not greater than the n value specified by the #pragma pack.