文章对于sizeof()分析得非常简单明了:http://blog.sina.com.cn/s/blog_7595927101019dff.html
对于一些复杂的例子,我再加入自己的想法。如以下例子:
struct A
{
int a;
double b;
float c;
};
struct B
{
char e[2];
int f;
double g;
short h;
struct A I;
};
以上的sizeof(A)和sizeof(B)分别是什么呢?
根据该文的思想,以及DEV C++4.9.9.2的运行情况,先分析sizeof(A)=24是怎么得来的。
A是double内存空间存储最大,是8个字节,而double要求首地址是8的倍数,那么A在内存中是这样的1111**** 11111111 1111**** 共24字节,其中1代表该类型实际在内存的字节空间,*代表根据需要补足的内存字节空间。
而对于sizeof(B)=48又是如何得来?
对于B,就要看A结构体的最大的那个类型,明显是double的8位最大啦,那么可以按照8的倍数为基准,
所以,我们先看变量
f是int ,所以char e[2]要补2字节先,也就是11**,
然后到int f 1111 共四个字节,那么char e[2]和int f刚好组成八字节,这么好运刚好符合下一个double g的8字节11111111,
然后到了h,必须是补6位,变成11******,
所以结合最后A的结构,得出最后的 11**(e[2]) 1111(b) 11111111(g) 11******(h) 1111**** 11111111 1111****(A)
最后得到的总字节数是48字节。
怎样?经过以上的分析是不是明白了许多呢?
附上运行程序和结果:
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
struct a{
char a;
short b;
char c;
};
struct b{
char c;
int d;
};
struct c{
char a;
b b1;
char f;
};
struct d{};
struct A
{
int a;
double b;
float c;
};
struct B
{
char e[2];
int f;
double g;
short h;
struct A I;
};
cout << sizeof(a)<<endl;
cout << sizeof(b) << endl;
cout << sizeof(c) << endl;
cout << sizeof(d)<<endl;
cout << sizeof(A)<< endl;
cout << sizeof(B) << endl;
system("PAUSE");
return EXIT_SUCCESS;
}