结构的存储和对齐Storage and Alignment of Structures

Microsoft 专用Microsoft Specific

结构成员按其声明顺序进行存储:第一个成员的内存地址最低,最后一个成员的内存地址最高。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. 对于结构,需求是其成员中的最大者。For structures, the requirement is the largest 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.

为了节省空间或遵循现有数据结构,您可能需要或多或少的简洁存储结构。To conserve space or to conform to existing data structures, you may want to store structures more or less compactly. /Zp[n] 编译器选项和 #pragma pack 控制将结构数据“打包”到内存中的方式。The /Zp[n] compiler option and the #pragma pack control how structure data is "packed" into memory. 使用 /Zp[n] 选项(其中,n 为 1、2、4、8 或 16)时,第一个结构成员后的每个结构成员将存储在字节边界上,这些字节边界是字段或包装大小 (n) 的对齐需求(以较小者为准)。When you use the /Zp[n] option, where n is 1, 2, 4, 8, or 16, each structure member after the first is stored on byte boundaries that are either the alignment requirement of the field or the packing size (n), whichever is smaller. 表示为公式,字节边界为Expressed as a formula, the byte boundaries are the

min( n, sizeof( item ) )  

其中,n 是使用 /Zp[n] 选项表示的包装大小,而 item 是结构成员。where n is the packing size expressed with the /Zp[n] option and item is the structure member. 默认包装大小为 /Zp8。The default packing size is /Zp8.

若要使用 pack 杂注为特定结构指定命令行上指定的包装以外的包装,请在结构的前面提供 pack 杂注,其中包装大小为 1、2、4、8 或 16。To use the pack pragma to specify packing other than the packing specified on the command line for a particular structure, give the pack pragma, where the packing size is 1, 2, 4, 8, or 16, before the structure. 若要恢复命令行上提供的包装,请指定不带参数的 pack 杂注。To reinstate the packing given on the command line, specify the pack pragma with no arguments.

位域默认为 Microsoft C 编译器的 long 大小。Bit fields default to size long for the Microsoft C compiler. 基于类型的大小或 /Zp[n] 大小(以较小者为准)对齐结构成员。Structure members are aligned on the size of the type or the /Zp[n] size, whichever is smaller. 默认大小为 4。The default size is 4.

结束 Microsoft 专用END Microsoft Specific

另请参阅See Also

结构声明Structure Declarations