#include //There are two factors at play for why our struct is taking up 12 bytes of memory //1. C and C++ require that the members of a structure are allocated in declaration order // This means that the address in memory for first must be less than second and second less than third //2. Processors either require or prefer that types are alligned in memory such that they begin on an //address boundry that is some multiple of it's size so if second was placed after first it would be //misaligned //So what we are seeing here is that the second member is padded so that it is ensured to falls on a //on a 4 byte boundry relative to the start of the structure //typedef struct //{ // // short first; //xx__ // int second; //xxxx // short third; //xx__ //this end is padded to ensure that if multiple structures were in an array that they would also be aligned //} Layout; //reordering can help align memory and reduce memory usage // This results in an 8 byte struct typedef struct { short first; //xx short third; //xx int second; //xxxx } Layout; int main() { printf("short: (%d) bytes\n", (int) sizeof(short)); printf("int: (%d) bytes\n", (int) sizeof(int)); //What is interesting is that the struct as a whole occupies 12 bytes not 8 like we thought printf("struct: (%d) bytes\n", (int) sizeof(Layout)); return 0; }