我试图检查结构数组包含的字节数。
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;
}
输出结果为:
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
结构数组占用128个字节,对于8个结构,每个结构占16个字节。但是每个结构都包含一个4字节的int和一个10字符的字符串数组,它应该是另外10个字节。因此,一个结构应该包含10 + 4 = 14个字节。但似乎有16个。其他2个字节来自哪里?
使用char name[13];
输出为:
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
使用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
所以,似乎struct
大小是4(16 - 20 - 24)的倍数,但为什么呢?如何计算或确定尺寸以及适用的规则?