Fork me on GitHub

每日一练0810--结构体内存对齐

每日一练0810--结构体内存对齐

typedef struct bb

{

    int id;  

    double weight; 

    float height; 

}BB;

 

typedef struct aa

{

    char name[2];

    int  id;

    short score;

    short grade; 

    BB b;

}AA;

这两个结构体 分别占用多大的内存,为什么?

结构体BB占24个字节,结构体AA占12个字节。因为结构内存对齐原则,结构体的总大小,为其成员中所含最大类型的整数倍。

结构体BB中,最大的数据类型是double 8个字节,变量id 为int 类型占4个字节,但weight为double类型占8个字节,8+4>8,所以id占8个字节的内存大小,weight占8个字节的内存大小,height占8个字节的内存大小,所以结构体BB总共占24个字节,BB在内存中的结构图为:

 

 

结构体AA的最大数据类型为结构体b的最大数据类型,即b中的变量weight的大小8个字节,所以AA的内存大小是8的整数倍。变量name占2个字节,id 占4个字节,score占2个字节,所以前3个变量占8个字节,grade占8个字节,结构体b占24个字节,所以结构体AA占40字节。AA在内存中的结构图为:

 

#include <stdio.h>

typedef struct
{
    int id;
    double weight;
    float height;
}BB;

typedef struct 
{
    char name[2];
    int id;
    short score;
    short grade;
    BB b;
}AA;

int main()
{
    printf("sizeof(BB): %d\n", sizeof(BB));
    printf("sizeof(AA): %d\n", sizeof(AA));
    
    return 0;
}

输出结果:

 

posted @ 2020-08-10 21:03  小黑子杜  阅读(167)  评论(0编辑  收藏  举报