Possible Duplicate:
struct sizeof result not expected
I have this C++ struct:
struct bmp_header {
//bitmap file header (14 bytes)
char Sign1,Sign2; //2
unsigned int File_Size; //4
unsigned int Reserved_Dword; //4
unsigned int Data_Offset; //4
//bitmap info header (16 bytes)
unsigned int Dib_Info_Size; //4
unsigned int Image_Width; //4
unsigned int Image_Height; //4
unsigned short Planes; //2
unsigned short Bits; //2
};
It is supposed to be 30 bytes, but ‘sizeof(bmp_header)’ gives me value 32. What’s wrong?
The reason is because of padding. If you put the
chars at the end of the struct,sizeofwill probably give you 30 bytes. Integers are generally stored on memory addresses that are multiples of 4. Therefore, since the chars take up 2 bytes, there are two unused bytes between it and the first unsigned int.char, unlikeint, is not usually padded.In general, if space is a big concern, always order elements of
structsfrom largest in size to smallest.Note that padding is NOT always (or usually) the
sizeof(element). It is a coincidence thatintis aligned on 4 bytes andcharis aligned on 1 byte.