sizeof总结

         以往使用sizeof计算struct时经常会有一些事实而非的问题,今天来把它彻底的解决一下,

 下面使用的是vc 6.0,主要是vc 6.0 中使用的内存分配都是没有进行优化的,所有便于学习。

下面先来看段程序:

struct A{
    char a[17];
};

struct B{
     struct A a;
     short int b;
}

void test(){
    cout<<"The size of struct A is "<<sizeof(struct A)<<endl;
    cout<<"The size of struct B is"<<sizeof(struct B)<<endl;
}



运行test的输出结果是

The size of struct A is 17

The size of struct B is 20

注:struct A的大小是以char类型来对其的所以是17,struct B是以short Int 数据类型来对齐的所以是20

程序2:

struct A{
    char a[17];
};

struct B{
     struct A a;
     int b;
}

void test(){
    cout<<"The size of struct A is "<<sizeof(struct A)<<endl;
    cout<<"The size of struct B is"<<sizeof(struct B)<<endl;
}



运行test的输出结果是

The size of struct A is 17

The size of struct B is 24

注:struct A的大小是以char类型来对其的所以是17,struct B是以Int 数据类型来对齐的所以是24

程序3:

struct A{
    char a[17];
};

struct B{
     struct A a;
     double b;
}

void test(){
    cout<<"The size of struct A is "<<sizeof(struct A)<<endl;
    cout<<"The size of struct B is"<<sizeof(struct B)<<endl;
}


运行test的输出结果是

The size of struct A is 17

The size of struct B is 32

 

注:struct A的大小是以char类型来对其的所以是17,struct B是以double数据类型 来对齐的所以是32

总结上面你会发现,每次的对齐都是以结构体中数据类型最长的那个数据类型来对齐

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值