sizeof(struct)

  • 在C语言中,结构体会以占用字节最长的变量为基准,做内存对齐。
#include<iostream>
#include<stdlib.h>
using namespace std;

struct A
{
    //4+4 = 8
    char c;
    int i;  
};

struct B
{
    //4+8+4 = 16 
    char c;
    A a;
    char b;
};

struct C
{
    //4 + 4*4 + 4 = 24
    char c;
    int a[4];
    int i;  
};

struct D
{   
    //4 + 4 = 8
    char c;
    char b;
    int q;  
};

struct E
{
    //8+8 = 16,以最大的为准,进行对齐填充 
    int a;
    double b;   
};

struct F
{   
    //1 + 1 = 2
    char a;
    char b;
};

int main()
{   
    cout<<"the sizeof struct A: "<<sizeof(A)<<endl;
    cout<<"the sizeof struct B: "<<sizeof(B)<<endl;
    cout<<"the sizeof struct C: "<<sizeof(C)<<endl;
    cout<<"the sizeof struct D: "<<sizeof(D)<<endl;
    cout<<"the sizeof struct E: "<<sizeof(E)<<endl;
    cout<<"the sizeof struct F: "<<sizeof(F)<<endl;
    return 0;   
} 
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容