I know that a char and an int are calculated as being 8 bytes on 32 bit architectures due to alignment, but I recently came across a situation where a structure with 3 shorts was reported as being 6 bytes by the sizeof operator. Code is as follows:
#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 ;
}
Compiler : g++ (Debian 4.3.2-1.1) 4.3.2. This really puzzles me, why isn’t alignment enforced for the structure containing 3 shorts?
That’s because
intis 4 bytes, and has to be aligned to a 4-bytes boundary. This means that ANYstructcontaining anintalso has to be aligned to at least 4-bytes.On the other hand,
shortis 2 bytes, and needs alignment only to a 2-bytes boundary. If astructcontainingshorts does not contain anything that needs a larger alignment, thestructwill also be aligned to 2-bytes.