[i][b]本文为firedragonpzy原创,转载务必在明显处注明:
转载自【Softeware MyZone】原文链接: http://www.firedragonpzy.com.cn/index.php/archives/1025[/b][/i]
有关sizeof详细可参考:[url]http://firedragonpzy.d3.tuidc.com/index.php/archives/1015[/url]
转载自【Softeware MyZone】原文链接: http://www.firedragonpzy.com.cn/index.php/archives/1025[/b][/i]
今天在研究sizeof的时候发现了一些比较有趣的现象,代码如下:
string str = "tr";
cout<<str.size()<<endl;//2
cout<<strlen(str.c_str())<<endl;//2
cout<<sizeof(str)<<endl;//32
cout<<str[1]<<endl;//r
//cout<<"tr".size()<<endl;//报错
cout<<strlen("tr")<<endl;//2
cout<<sizeof("tr")<<endl;//3
cout<<"tr"[2]<<endl;空白
事实表明,str和"tr"是不一样的,str是个string类型的对象,占据32位byte的空间,而"tr"是char类型的数组,末尾均以"\0"填充,而string类型的str是不以"\0"填充,这个是被string类型处理了。一个str和"tr"很明显的区别就是"tr"根本就没有size()的方法。
再说下sizeof和strlen的区别:
sizeof:取得是实际变量占据的内存空间
strlen:取得是除去"\0"后变量占据的内存空间
有关sizeof详细可参考:[url]http://firedragonpzy.d3.tuidc.com/index.php/archives/1015[/url]