您的位置:首页 > 其它

字符串中sizeof和strlen的区别,以及'\0'与NULL的区别

2015-05-22 11:45 253 查看

程序

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char ss[]="0123456789";
cout<<strlen(ss)<<endl;
cout<<sizeof(ss)<<endl;
for(int i=0;i<strlen(ss);i++)
{
cout<<ss[i] <<endl;
}
cout<<'\0'<<endl;
cout<<NULL<<endl;
return 0;
}


运行结果



从中可以发现:

strlen(ss)的结果为10,而sizeof(ss)的结果却是11,这是为什么呢?

原因是当用字符串给字符数组赋值时,字符数组默认在其末尾加上结束标志,也就是’\0’,即字符数组的最后一个字符为’\0’。strlen()函数计算到结束标志的前一个字符,在这里是’9’,所以结果为10;而sizeof()则计算到结束标志,所以结果为10+1=11。

strlen()函数的实现:

int strlen(char s[])
{
int num=0;
int i=0;
while(s[i]!='\0')
{
num++;
i++;
}
return num;
}


打印’\0’时输出为空,而打印NULL却输出为0。后者是因为NULL在C++中值定义为0,但前者我就不知道了,哪位大神可以告诉我
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: