【C++】sizeof相关【总结篇】
2012-02-27 21:54
295 查看
先给出例题:
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
#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
相关文章推荐
- C/C++ sizeof总结
- C++ sizeof关键字的使用总结
- C++常见问题(三)——宏定义、const、static、sizeof的相关实例
- C++ sizeof的使用总结
- JNA调用C++的相关点总结
- C/C++中的sizeof相关【面试?】
- c++相关链接总结
- C++ sizeof的使用总结
- C++ sizeof的使用总结
- C++ sizeof的使用总结
- c/c++ sizeof总结
- c++中的位运算相关规律总结和口诀
- C++ sizeof用法总结
- C\C++ sizeof 陷阱&&总结
- C/C++中sizeof关键字总结
- C++ sizeof的使用总结
- C++继承相关知识点总结
- C++ 相关知识总结
- 【C++】继承类之sizeof计算_字节对齐【总结篇】
- 总结:关于Sizeof的相关知识