C语言:strlen()函数易错点
<pre name="code" class="cpp">/* strlen函数解析 */ # include<stdio.h> # include<malloc.h> # include<string.h> int main(void) { char * c1 = "AbSjhhss"; int len1 = strlen(c1); printf("len1 = %d\n", len1); //len1 = 8 char c2[] = {'a', '4', 'r', 't', 'd'}; int len2 = strlen(c2); printf("len2 = %d\n", len2); //..error..len2 = 9 char c3[] = {'a', '4', 'r', 't', 'd', '\0'}; int len3 = strlen(c3); printf("len3 = %d\n", len3); //len3 = 5 char c4[10] = "AbS"; int len4 = strlen(c4); printf("len4 = %d\n", len4); //len4 = 3 char c5[4]; int len5 = strlen(c5); printf("len5 = %d\n", len5); //len5 = 5 /* c5[0] = '\0'; len5 = strlen(c5); printf("len5 = %d\n", len5); //len5 = 0 */ c5[4] = '\0'; len5 = strlen(c5); printf("len5 = %d\n", len5); //len5 = 4 return 0; } /* 总结:如果字符数组, 1.用字符串(双引号"")初始化,用strlen函数可以求出该字符串的长度 2.用字符数组的形式({'',''})初始化,必须在最后面添加一个元素'\0'才可以。 所以:strlen() 从字符数组首地址开始,一直找下去,直到遇到'\0'才停止 */