以往使用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
总结上面你会发现,每次的对齐都是以结构体中数据类型最长的那个数据类型来对齐