Pack details

xiaoxiao2021-03-06  40

#pragma Pack (8)

Struct s1 {

Char a;

Long B;

}

Struct s2 {

Char C;

Struct S1 D;

Long long e;

}

#pragma pack ()

SizeOf (S2) results are 24.

Members have an important condition, that is, each member is aligned separately. Although each member is aligned in its own way.

That is to say, although the 8-byte alignment is specified, not all members are aligned with 8-byte. The rule of its alignment is, each member is aligned with the alignment parameters of its type (usually this type of size) And a smaller alignment in the specified alignment parameter (here is 8 bytes). And the length of the structure must be an integer multiple of all align parameters used, not enough to make up the fill byte.

In S1, member A is 1 byte default Press 1 byte alignment, specifying the alignment parameter 8, these two values ​​take 1, a Press 1 bytes; members B are 4 bytes, the default is 4 words The knight is aligned, then it is aligned at 4 bytes, so sizeof (S1) should be 8;

In the S2, the C and S1 are aligned, but D is a structure, it is 8 bytes, what is it aligned? For the structure, its default alignment is all of its members The largest one in the alignment parameter, S1 is 4. So, member D is aligned in 4 bytes. Member E is 8 bytes, it is the default, according to the 8-byte alignment, the same as the specified, so it On the 8-byte boundary, at this time, 12 bytes have been used, so add 4 bytes of empty, starting from the 16th byte to place member E. At this time, the length is 24, already It can be divided by 8 (member E to 8 bytes). This uses a total of 24 bytes.

a b

S1 memory layout: 11 **, 1111,

C S1.A S1.B D

S2 memory layout: 1 ***, 11 **, 1111, **** 11111111

There are three points here:

1. Each member is aligned in its own way, and minimizes the length.

2. The default alignment of complex types (such as structures) is the alignment of its longest member, so that when members are complex types, the length can be minimized.

3. The length of the alignment must be an integer multiple of the largest alignment parameters in the member, which can guarantee each boundary alignment when processing an array.

转载请注明原文地址:https://www.9cbs.com/read-53246.html

New Post(0)