【发布时间】:2011-02-09 05:21:38
【问题描述】:
我知道由于对齐,char 和 int 在 32 位架构上被计算为 8 个字节,但我最近遇到了一种情况,即 sizeof 运算符将具有 3 个短裤的结构报告为 6 个字节。代码如下:
#include <iostream>
using namespace std ;
struct IntAndChar
{
int a ;
unsigned char b ;
};
struct ThreeShorts
{
unsigned short a ;
unsigned short b ;
unsigned short c ;
};
int main()
{
cout<<sizeof(IntAndChar)<<endl; // outputs '8'
cout<<sizeof(ThreeShorts)<<endl; // outputs '6', I expected this to be '8'
return 0 ;
}
编译器:g++ (Debian 4.3.2-1.1) 4.3.2。这真的让我很困惑,为什么包含 3 个短裤的结构不强制对齐?
【问题讨论】: