Member alignment problem

xiaoxiao2021-03-06  15

#pragma pack (8) Struct S1 {char A; long b;}; struct s2 {char C; Struct S1 D; long long e;}; # prgma pack () sizeof (s2) result is 24. Members have one Important conditions, that is, each member is aligned separately. Although each member is aligned in his own way. That is to say, although the above is specified, all members are aligned with 8 bytes. It is aligned The rule is that each member is aligned according to the alignment parameters of its type (usually this type) and the specified alignment parameter (here is 8 bytes), and the length of the structure must be all aligned. The integer multiple of the parameters is not enough, and the completion byte. S1, member A is 1 byte default, according to 1 byte alignment, specify the alignment parameter 8, these two values ​​are 1, A Press 1 byte alignment; member B is 4 bytes, the default is to align in 4 bytes, then in the 4-byte alignment, SIZEOF (S1) should be 8; S2, the C and S1 are aligned, in one byte alignment, And D is a structure, it is 8 bytes, what is it aligned? For the structure, its default alignment is the biggest one in the alignment parameters used by all members, S1 is 4. So, members D is aligned in 4 bytes. Member E is 8 bytes, which is default 8-byte alignment, as specified, so it is on the 8-byte boundary, at this time, 12 words have been used The section, so adds 4 bytes of empty, starting from the 16th byte to place member E. At this time, the length is 24, can be 8 (member E Press 8 bytes aligned). This, a total 24 bytes were used. A BS1 memory layout: 11 **, 1111, c S1.A S1.B DS2 memory layout: 1 ***, 11 **, 1111, **** 11111111

There are three points here: 1. Each member is aligned separately, and minimizes the length. 2. The default alignment of complex types (such as structure) is the alignment of its longest member, so that members are complex in members. When the type, you can minimize length 3. Alignment must be an integer multiple of the largest alignment parameters in members, which can guarantee each boundary alignment when processing arrays.

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

New Post(0)