First of all, 'BM'
is two bytes, and cannot be fit into a single unsigned char
('BM'
is probably treated by your compiler as a multibyte literal, which is probably not what you want).
Then, the compiler is free to add padding inside a structure to align it to the correct word boundaries; on x86 correct members aligment guarantees much better read performances, on other architectures if the alignment is wrong you get a hardware exception.
In your case, for example, on 32-bit x86 the binary layout of your struct will be one byte of sig
, three bytes of padding, and then the reserved
int
(that will be aligned on 4-byte boundaries for optimal access speed).
There's no standard way to avoid padding; you have to resort to compiler-specific tricks. On VC++, you'll have to use #pragma pack
, supported also on g++ and clang, although their "native" way is to use __attribute__(packed)
.
By the way, if you have to write a "portable" file format to file (like the DIB you are trying to write) always use fixed-size integer types (from stdint.h
) and be ready to deal with endianness issues if you plan to port to other architectures.