代码之家  ›  专栏  ›  技术社区  ›  DCR

结构组件不相加

  •  -1
  • DCR  · 技术社区  · 3 年前

    我有以下内容:

    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;
    }
    

    现在,sizeof(temps)=160,sizeof sizeof(temps[0]。temp=4。

    既然城市和温度占了12,那么温度占了4呢[0]?

    1 回复  |  直到 3 年前
        1
  •  5
  •   pmacfarlane    3 年前

    此结构

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

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

    因此,该结构附加了4个字节。