- Sizeof()是一个运算符,而不是一个函数。
- 对于参数不同时,sizeof返回值表示的含义也是不同的:
**数组—分配的数组空间大小
指针—存储指针所用的空间大小
类型—该类型所占的空间大小
对象—对象实际占用空间的大小
函数—函数返回类型所占的空间大小**
- Strlen()是函数,需要头文件”string.h”
- 参数必须是字符型指针(char*),且必须是以’\0’结尾的。 当数组名作为参数传入时,实际上数组就退化成了指针
Eg:
int eg[10];
cout<< sizeof( eg ) <<endl;
cout<< strlen( eg ) <<endl;
[Error] cannot convert 'int*' to 'const char*' for argument '1' to 'size_t strlen(const char*)'
改变 eg[10]的类型:
char eg[10];
cout<< sizeof( eg ) <<endl;
cout<< strlen( eg ) <<endl;
10
0
--------------------------------
Process exited after 0.3467 seconds with return value 0
Sizeof返回定义arr数组时,编译器为其分配的数组空间大小,不关心里面存了多少数据。
Strlen只关心存储的数据内容,不关心控件的大小和类型
char x[10];
char y[10];
char z[10] = "";
cout<<" The result is : "<<endl;
cout<<"sizeof(x) = "<<sizeof( x )<<"\tstrlen(x) = "<<strlen( x )<<endl;
cout<<"sizeof(y) = "<<sizeof( y )<<"\tstrlen(y) = "<<strlen( y )<<endl;
cout<<"sizeof(z) = "<<sizeof( z )<<"\tstrlen(z) = "<<strlen( z )<<endl;
The result is :
sizeof(x) = 10 strlen(x) = 3
sizeof(y) = 10 strlen(y) = 1
sizeof(z) = 10 strlen(z) = 0
--------------------------------
Process exited after 0.2898 seconds with return value 0
请按任意键继续. . .
实际上每次运行可能不一样,这取决于指针里面存了什么(从parr[0]开始知道遇到第一个NULL结束);