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?
It doesn't give a wrong measurement. You need to learn about alignment and padding.
The compiler can add padding in between structure members to respect alignment constraints. That said, it's possible to control padding with compiler specific directives (see GCC variable attributes or MSVC++ pragmas).
The reason is because of padding. If you put the char
s at the end of the struct, sizeof
will 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
, unlike int
, is not usually padded.
In general, if space is a big concern, always order elements of structs
from largest in size to smallest.
Note that padding is NOT always (or usually) the sizeof(element)
. It is a coincidence that int
is aligned on 4 bytes and char
is aligned on 1 byte.
struct bmp_header {
char Sign1,Sign2; //2
// padding for 4 byte alignment of int: // 2
unsigned int File_Size; //4
unsigned int Reserved_Dword; //4
unsigned int Data_Offset; //4
unsigned int Dib_Info_Size; //4
unsigned int Image_Width; //4
unsigned int Image_Height; //4
unsigned short Planes; //2
unsigned short Bits; //2
};
2+2+4+4+4+4+4+4+2+2 = 32. Looks correct to me. If you expect 30 it means you expect 1 byte padding, as in :
#pragma pack(push)
#pragma pack(1)
struct bmp_header {
char Sign1,Sign2; //2
unsigned int File_Size; //4
unsigned int Reserved_Dword; //4
unsigned int Data_Offset; //4
unsigned int Dib_Info_Size; //4
unsigned int Image_Width; //4
unsigned int Image_Height; //4
unsigned short Planes; //2
unsigned short Bits; //2
};
#pragma pack(pop)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With