定义
sizeof是C/C运算符(关键字),用于计算对象或类型在内存中占用的字节数。
strlen是c语言的库函数,用于计算字符串的长度。 不包括末尾0。
引用头文件#include。
函数原型: size_tStrlen(constchar*s ) ) ) ) ) ) ) )。
注意: sizeof是关键字,不是函数。 strlen是一个函数。
举个例子
char test[20]=“hello”;
char *test1=“hello!” ;
char test2[]=“hello! ”;
Strlen(test )//5 strlen计算字符串的实际长度,不包括结尾0,而是以第一个’ 0’作为结尾进行计算。
由Sizeof(test )/20定义的char类型数组占用20个字节。
Strlen(test1 )//6 trlen计算字符串的实际长度,不包含末尾0,以第一个’ 0’为结尾。
Sizeof(test1 )/8计算指针类型所在的字节数,取决于32/64位计算机,32位占4字节,64位占8字节。
Strlen(test2)//7 strlen计算字符串的实际长度,不包括结尾0,而是以第一个’ 0’作为结尾进行计算。
在Sizeof(test2)/8中定义的char类型数组占用8个字节,其中包含终结符() 0。
strlen的返回值为无符号整型,无符号。
1.if(strlen(test )=strlen (test2) )
2.if (strlen (测试)-strlen (测试2 )=0) )。
3.if(strlen(test )=2) ) ) ) ) ) ) ) ) )。
4.if(Strlen(test )- 10=0) ) ) ) ) ) ) )。
两个公式看起来是相同的效果。 第1、3个表达式写得正确,第2、4个表达式的strlen返回值为unsigned int型且无符号,因此表达式永远为真。
可以通过强制将strlen返回值转换为int来解决上述问题。