您的位置:首页 > 编程语言 > C语言/C++

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

2012-02-27 21:54 295 查看
先给出例题:

#include<iostream>
using namespace std;
struct rec_s
{
long lIndex;
short sLevel[6];
char cPos;
};
union u
{
char a[13];
int b;
};
void main()
{
rec_s stMax,*pMax;
char str[]="Hello";
char *pChar=str;
unsigned long ulGrade=10;
unsigned short usClass=10;
double dWeight;
unsigned char *pCharArray[10][10];

cout<<sizeof(stMax)<<endl;//20
cout<<sizeof(pMax)<<endl;
cout<<sizeof(str)<<endl;//6
cout<<sizeof(pChar)<<endl;
cout<<sizeof(ulGrade)<<endl;
cout<<sizeof(usClass)<<endl;
cout<<sizeof(dWeight)<<endl;
cout<<sizeof(pCharArray)<<endl;//400

cout<<"Union u:"<<sizeof(u)<<endl;
}


vs2008运行结果:

20
4
6
4
4
2
8
400
Union u:16

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

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

sizeof计算相关:
指针的sizeof为4,例sizeof(pMax), sizeof(pChar);

无空间说明的字符数组为长度+1,例sizeof(str);

有空间说明的数组为[类型sizeof]*元素个数,例sizeof(pCharArray);

区别于struct的,union的sizeof计算:
首先确认对齐数;

取成员中占用空间最大的,大于该值(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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: