为什么由char,short和char(按顺序)组成的结构体在使用4字节打包启用的C ++中编译时,会得到一个6字节的结构体? [英] Why does a struct consisting of a char, short, and char (in that order), when compiled in C++ with 4-byte packing enabled, come to a 6-byte struct?

查看:419
本文介绍了为什么由char,short和char(按顺序)组成的结构体在使用4字节打包启用的C ++中编译时,会得到一个6字节的结构体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以为我明白了C / C ++如何处理结构体成员对齐。但是我在Visual Studio 2008和2010中得到了一个奇怪的结果。

I thought I understood how C/C++ handled struct member alignment. But I'm getting strange results for a particular arrangement in Visual Studio 2008 and 2010.

具体来说,我发现一个由char,short和char被编译成一个6字节的结构,甚至启用了4或8字节打包。我失去了为什么会这样。我可以理解一个4字节的结构。我可能理解一个8字节的结构。但是我认为,当启用4字节打包时,6字节的结构是不可能的。

Specifically, I'm finding that a struct consisting of a char, short, and char is compiled into a 6-byte struct, even with 4- or 8-byte packing enabled. I am at a loss as to why this would be. I can understand a 4-byte struct. I could perhaps understand an 8-byte struct. But I would think that a 6-byte struct would be impossible when 4-byte packing is enabled.

一个程序演示的问题是:

A program that demonstrates the problem is:

#include <iostream>
using namespace std;

#pragma pack (4)

struct Alignment
{
 char c1;
 short s;
 char c2;
};

#define REPORT_VAR_POSITION( structName, varName ) cout << "Member '" << #varName << "' sits at byte # " << offsetof( structName, varName ) << "." << endl;

int main(int argc, char* argv[])
{
 cout << "Sizeof struct Alignment is " << sizeof( Alignment ) << " bytes." << endl;
 REPORT_VAR_POSITION( Alignment, c1 );
 REPORT_VAR_POSITION( Alignment, s );
 REPORT_VAR_POSITION( Alignment, c2 );

 system( "pause" );

 return 0;
}

输出为:

Sizeof struct Alignment is 6 bytes.
Member 'c1' sits at byte # 0.
Member 's' sits at byte # 2.
Member 'c2' sits at byte # 4.
Press any key to continue . . .


$ b < b $ b

Can anyone explain why VC is padding each of those chars with an additional byte?

推荐答案

MSDN文档 #pragma pack (其中 n 是您设置的值):


成员的对齐方式将位于 n

The alignment of a member will be on a boundary that is either a multiple of n or a multiple of the size of the member, whichever is smaller.

sizeof(short )是两个字节,小于您设置的四个字节的打包值,因此 short 成员对齐到两个字节边界。

sizeof(short) is two bytes, which is smaller than the packing value of four bytes that you set, so the short member is aligned to a two byte boundary.

最后 char c2 )后面有一个额外的字节,所以当 Alignment 对象放在数组中时, short 在两个字节的边界。数组元素是连续的,并且它们之间没有填充,因此必须将填充添加到结构的末尾,以确保数组中的正确对齐。

The last char (c2) is padded with an extra byte after it so that when Alignment objects are placed in an array, the short element is still correctly aligned on a two-byte boundary. Array elements are contiguous and there can be no padding between them, so padding must be added to the end of the structure in order to ensure proper alignment in arrays.

这篇关于为什么由char,short和char(按顺序)组成的结构体在使用4字节打包启用的C ++中编译时,会得到一个6字节的结构体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆