alignment - In C++11, why does int16_t have a size of 4 when declared after a float inside a struct? -


i have data structure this:

struct mystruct {     float f;     int16_t i; }; 

sizeof(int16_t) gives 2, sizeof(mystruct) gives 8 instead of 6. why that? how can declare int16_t variable of 2 bytes inside data structure?

that because of padding, given system's architecture, compiler adds space structure.

if try add int16_t, you'll see size of structure still 8.

struct mystruct {     float f;     std::int16_t i;     std::int16_t g; }; 

in original case

struct mystruct {     float f;     std::int16_t i;     //2 bytes padding }; 

note can have padding in between members in structure, why advice sort members decreasing order size, minimize padding.

you can have quick read @ corresponding wikipedia page, written. http://en.wikipedia.org/wiki/data_structure_alignment#typical_alignment_of_c_structs_on_x86


Comments