Each non-first field in a structure may be preceded by a gap (or padding). The compiler is adding gaps to fit the need of your processor and of the ABI conventions.
You should trust the compiler, it is laying out struct
as required by the implementation.
Some compilers provide extensions to alter or improve the structure's layout, e.g. the type attributes of GCC for aligned
or packed
.
Don't feel the paddings and gaps inside a struct
as an issue, but as asset: the compiler tries very hard to satisfy the processor, the ABI conventions, etc...
Most compilers don't reorder fields in structures (GCC used to have a rarely useful optimization which did that, but that optimization has been removed, because sometimes it hurted - e.g. with LTO).
If you care about struct
size and if you don't care about the order of the fields, you may reorder them cleverly. But the most dense order could be architecture dependent.
BTW, the C standard does not even guarantee that an int
is 32 bits or of a larger size and alignment than char
(even if that is very common). It provides <stdint.h>
and int32_t
for that purpose. I suspect you would not observe any padding or gap if compiling for a 16 bits machine on which int
-s are 16 bits (e.g. the original PC AT with Intel 8086 processor from the 1980s, or some cheap 16 bits microcontroller).