strlen与sizeof区别

来源:互联网 发布:淘宝需要开定位吗 编辑:程序博客网 时间:2024/05/16 11:57

例1:

#include<iostream>#include<string.h>//strlen()的头文件using namespace std;int main(){   char s[5];   strcpy(s,"cat");   cout<<strlen(s)<<" "<<sizeof(s)<<endl;    system("pause");}
结果是 3 5。

strlen判断s中字符串的长度 为 3
sizeof判断s数组的大小 为 5

例2:

#include<iostream>#include<string>using namespace std;int main(){  char *s="hello";  char s1[]="hello";  string a="hello";  cout<<"sizeof(s): "<<sizeof(s)<<endl;//s指针的大小   cout<<"sizeof(a): "<<sizeof(a)<<endl; //string类对象的大小,类似于sizeof(char)   cout<<"strlen(s): "<<strlen(s)<<endl;//字符串长度   cout<<"strlen(s1): "<<strlen(s1)<<endl;//字符串长度   cout<<"sizeof(s1)/sizeof(char): "<<sizeof(s1)/sizeof(char)<<endl;//字符数组长度,是字符串长度+1.   cout<<"sizeof(s1):"<<sizeof(s1)<<endl;//sizeof(数组名),得到的是数组大小。  cout<<"a.length():f "<<a.length()<<endl;//string型字符串长度   system("pause");  return 0;} 


原创粉丝点击