【C++】sizeof相关【总结篇】

先给出例题:

 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

--------------------------------------------

从上面可以总结出以下要点:

  • sizeof计算相关:
    1. 指针的sizeof为4,例sizeof(pMax), sizeof(pChar);
    2. 无空间说明的字符数组为长度+1,例sizeof(str);
    3. 有空间说明的数组为[类型sizeof]*元素个数,例sizeof(pCharArray);
  • 区别于struct的,union的sizeof计算:
    1. 首先确认对齐数;
    2. 取成员中占用空间最大的,大于该值(13)且为对齐数(4)的倍数的最小值(16),参照上例中Union u;
  • 与字符相关的占用空间计算之sizeof与strlen的区别:
    • sizeof为运算符,strlen为函数;
    • sizeof编译时确定,strlen运行时确定;
    • char a[100]="123",则sizeof(a)=100,strlen(a)=3;
    • sizeof a(不加括号也成立,因为其为运算符);
    • strlen只能用字符串地址做参数,int a[100],则strlen(a)语法错误,因为strlen是计算开始到'\0'之间的字符数;

注:pCharArray是一个两维数组,该数组有100个元素,每个元素都是无符号字符型的指针,故sizeof(pCharArray)是数组的sizeof,不是指针的sizeof!

另外,继承类之sizeof计算,见本人博客http://www.cnblogs.com/caixu/archive/2011/10/11/2207423.html

原文地址:https://www.cnblogs.com/caixu/p/2370476.html