language is C with gcc compiler
if i make a struct like so
struct test {
char item_1[2];
char item_3[4];
char item_4[2];
char item_5[2];
char item_6[4];
};
and i do a sizeof(struct test) it returns 14(bytes). which is the expected result.
but if i do
struct test {
int16_t item_1;
int32_t item_3;
int16_t item_4;
int16_t item_5;
int32_t item_6;
};
sizeof(struct test) will return something strange like 44. when i debug using gnu ddd i can see inside the structure and see that it all looks normal and all items have the expected number of bytes.
so why is the sizeof operator returning a unexpected value ?
Compilers may insert padding between struct members, or after the last member. This is normally done to satisfy alignment requirements. For example, an
int32_tobject might require 4-byte alignment, so the compiler inserts 2 bytes of padding between the first and second members. The details will vary depending on the platform.