我知道在32位架构下,由于对齐方式的影响,char和int的大小都被计算为8个字节。但最近我遇到了这样一种情况:一个拥有3个short的结构体通过sizeof操作符报告其大小为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个short的结构体没有执行对齐?
#define alignof(type) ((char *)&((struct { char dummy; type x; } *)0)->x - (char *)0)
- R.. GitHub STOP HELPING ICE