I was trying to check the number of bytes an array of structures contains.
struct coins {
int value;
char name[10];
}
int main() {
struct coins allCoins[8];
printf("Total size of the array of structures = %d bytes \n", sizeof(allCoins)); // == 128 bytes (containing 8 structures => 16 bytes / structure)
printf("Size of a structure within the array of structures = %d bytes \n", sizeof(allCoins[0]));
printf("Size of the 'value' variable of the structure within the array of structures = %d bytes \n", sizeof(allCoins[0].value));
printf("Size of the 'name' string array of the structure within the array of structures = %d bytes \n", sizeof(allCoins[0].name));
return 0;
}
The output is:
Total size of the array of structures = 128 bytes
Size of a structure within the array of structures = 16 bytes
Size of the 'value' variable of the structure within the array of structures = 4 bytes
Size of the 'name' string array of the structure within the array of structures = 10 bytes
The array of structures takes 128 bytes, for 8 structures this makes 16 bytes per structure. Each structure however contains an int which is 4 bytes and a string array of 10 characters which should be another 10 bytes. So, totally a structure should contain 10 + 4 = 14 bytes. But it seems it has 16. Where are the other 2 bytes coming from ?
With char name[13];
the output is:
Total size of the array of structures = 160 bytes
Size of a structure within the array of structures = 20 bytes
Size of the 'value' variable of the structure within the array of structures = 4 bytes
Size of the 'name' string array of the structure within the array of structures = 13 bytes
And with char name[17];
:
Total size of the array of structures = 192 bytes
Size of a structure within the array of structures = 24 bytes
Size of the 'value' variable of the structure within the array of structures = 4 bytes
Size of the 'name' string array of the structure within the array of structures = 17 bytes
So, it seems that the struct
size is a multiple of 4 (16 - 20 - 24) but why ? How is the size calculated or determined and what rules apply ?