先给出例题:
1 #include<iostream>
2 using namespace std;
3 struct rec_s
4 {
5 long lIndex;
6 short sLevel[6];
7 char cPos;
8 };
9 union u
10 {
11 char a[13];
12 int b;
13 };
14 void main()
15 {
16 rec_s stMax,*pMax;
17 char str[]="Hello";
18 char *pChar=str;
19 unsigned long ulGrade=10;
20 unsigned short usClass=10;
21 double dWeight;
22 unsigned char *pCharArray[10][10];
23
24 cout<<sizeof(stMax)<<endl;//20
25 cout<<sizeof(pMax)<<endl;
26 cout<<sizeof(str)<<endl;//6
27 cout<<sizeof(pChar)<<endl;
28 cout<<sizeof(ulGrade)<<endl;
29 cout<<sizeof(usClass)<<endl;
30 cout<<sizeof(dWeight)<<endl;
31 cout<<sizeof(pCharArray)<<endl;//400
32
33 cout<<"Union u:"<<sizeof(u)<<endl;
34 }
vs2008运行结果:
20
4
6
4
4
2
8
400
Union u:16
--------------------------------------------
从上面可以总结出以下要点:
注:pCharArray是一个两维数组,该数组有100个元素,每个元素都是无符号字符型的指针,故sizeof(pCharArray)是数组的sizeof,不是指针的sizeof!
另外,继承类之sizeof计算,见本人博客http://www.cnblogs.com/caixu/archive/2011/10/11/2207423.html