结构成员的填充和对齐Padding and Alignment of Structure Members

ANSI 3.5.2.1 结构的成员的填充和对齐方式,以及位域是否可以跨存储单元边界ANSI 3.5.2.1 The padding and alignment of members of structures and whether a bit field can straddle a storage-unit boundary

结构成员按其声明顺序进行存储:第一个成员的内存地址最低,最后一个成员的内存地址最高。Structure members are stored sequentially in the order in which they are declared: the first member has the lowest memory address and the last member the highest.

每个数据对象具有 alignment-requirement。Every data object has an alignment-requirement. 所有数据(结构、联合和数组除外)的对齐要求是对象的大小或当前打包大小(使用 /Zp 或 pack 杂注指定,以较小者为准)。The alignment-requirement for all data except structures, unions, and arrays is either the size of the object or the current packing size (specified with either /Zp or the pack pragma, whichever is less). 对于结构、联合和数组,对齐要求是其成员的最大对齐要求。For structures, unions, and arrays, the alignment-requirement is the largest alignment-requirement of its members. 为每个对象分配一个 offset,以便Every object is allocated an offset so that

offset % alignment-requirement == 0offset % alignment-requirement == 0

如果整型的大小相同,并且下一个位域适合当前分配单元而未跨位域的常见对齐需求所强加的边界,则将相邻位域打包到相同的 1 字节、2 字节或 4 字节分配单元中。Adjacent bit fields are packed into the same 1-, 2-, or 4-byte allocation unit if the integral types are the same size and if the next bit field fits into the current allocation unit without crossing the boundary imposed by the common alignment requirements of the bit fields.

另请参阅See Also

结构、联合、枚举和位域Structures, Unions, Enumerations, and Bit Fields