结构组件不相加

DCR*_*DCR -2 c memory struct sizeof memory-alignment

我有以下内容:

typedef struct
{
    string city;
    int temp;
}
avg_temp;

avg_temp temps[NUM_CITIES];

void sort_cities(void);

int main(void)
{
    temps[0].city = "Austin";
    temps[0].temp = 97;

    temps[1].city = "Boston";
    temps[1].temp = 82;

    temps[2].city = "Chicago";
    temps[2].temp = 85;

    temps[3].city = "Denver";
    temps[3].temp = 90;

    temps[4].city = "Las Vegas";
    temps[4].temp = 105;

    temps[5].city = "Los Angeles";
    temps[5].temp = 82;

    temps[6].city = "Miami";
    temps[6].temp = 97;

    temps[7].city = "New York";
    temps[7].temp = 85;

    temps[8].city = "Phoenix";
    temps[8].temp = 107;

    temps[9].city = "San Francisco";
    temps[9].temp = 66;
}
Run Code Online (Sandbox Code Playgroud)

现在,sizeof(temps) = 160、sizeof(temps[0]) = 16、sizeof(temps[0].city) = 8 和 sizeof(temps[0].temp = 4。

由于 city 和 temp 占用 12,temps[0] 中什么占用 4?

Vla*_*cow 5

这个结构

typedef struct
{
    string city;
    int temp;
}
avg_temp;
Run Code Online (Sandbox Code Playgroud)

根据大小等于 8 的类型string(显然是 type 的别名)的数据成员的更严格对齐进行对齐。char *

所以该结构体附加了4个字节。