strlen()、size()、sizeof()的区别
1.strlen()
strlen是一个C语言中的一个字符串函数,使用strlen返回的是字符串实际的大小,在程序的运行过程中计算。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int main()
{
int res;
char str1[10]="hello";
res=strlen(str1); //res=5
cout << res << endl<<endl<<endl;
char str2[]="hello";
res=strlen(str2); //res=5
cout << res << endl<<endl<<endl;
char *str3="hello";
res=strlen(str3); //res=5
cout << res << endl<<endl<<endl;
return 0;
}
运行结果如下:
可以看到,结果均等于5,说明strlen返回的均是字符串的实际长度。
2.size()
(1)在获取字符串长度的时候,size()、strlen()、length()的结果是一样的。
(2)在对容器操作时,返回的是容器中元素的个数。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
int main()
{
char str1[10]="hello";
cout << sizeof(str1) <<endl; //10
char str2[]="hello";
cout << sizeof(str2) << endl; //6
cout << sizeof(*str2) <<endl; //1,*str2是第一个char字符,则为1
strcpy(str2,"abc"); //给str2重新赋值为"abc",其结果仍然不会改变
cout << sizeof(str2) << endl; //6
char *str3="hello";
cout << sizeof(str3) <<endl; //4
int a[10];
cout << sizeof(a) << endl; //40
int b;
cout << sizeof(b) << endl; //4
char c;
cout << sizeof(c) << endl; //1
vector <int> d(10,1);
cout << sizeof(d) <<endl; //12
vector <int> e;
cout << sizeof(e) <<endl; //12
return 0;
}
运行结果:
3.sizeof()
sizeof是运算符,该类型保证能容纳实现所建立的最大对象的字节大小,其值在编译时即计算好了,它的值不会随着内容的改变而发生变化,记住“不会随内容的改变发生变化”这句话,那下面这些例子就很好理解了:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
int main()
{
char str1[10]="hello";
cout << sizeof(str1) <<endl; //10
char str2[]="hello";
cout << sizeof(str2) << endl; //6
cout << sizeof(*str2) <<endl; //1,*str2是第一个char字符,则为1
strcpy(str2,"abc"); //给str2重新赋值为"abc",其结果仍然不会改变
cout << sizeof(str2) << endl; //6
char *str3="hello";
cout << sizeof(str3) <<endl; //4
int a[10];
cout << sizeof(a) << endl; //40
int b;
cout << sizeof(b) << endl; //4
char c;
cout << sizeof(c) << endl; //1
return 0;
}