The following is my test file:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str1[10] = "123456789";
char str2[10] = "1234567890abcd";
char str3[10] = "12345";
char str4[10] = "12345 12";
char str5[10] = {‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘\0‘, ‘5‘, ‘6‘};
int len1, len2, len3, len4, len5;
len1 = strlen(str1);
len2 = strlen(str2);
len3 = strlen(str3);
len4 = strlen(str4);
len5 = strlen(str5);
printf("str1--> %s, len-->%d\n", str1, len1);
printf("str2--> %s, len-->%d\n", str2, len2);
printf("str3--> %s, len-->%d\n", str3, len3);
printf("str4--> %s, len-->%d\n", str4, len4);
printf("str5--> %s, len-->%d\n", str5, len5);
printf("====== Game Over ======\n");
printf("\n");
return 0;
}
The following is my test result:
str1--> 123456789, len-->9
str2--> 1234567890123456789, len-->19
str3--> 12345, len-->5
str4--> 12345 12, len-->8
str5--> 1234, len-->4
====== Game Over ======
Result Analysis: based on the result of "Man strlen", strlen () calculates the length of string S, but does not include the ending character '\ 0 '. Therefore, the '\ 0' character indicates the end of a string. In my test:
| Str1 |
The length is easy to know.
|
| Str2 |
Why is the str2 length incorrect? This is because the "ABCD" character cannot be stored in a storage unit with a length of 10 in str2, and it cannot be allocated or stored out of bounds, therefore, "ABCD" is not allocated to storage units, and the end character '\ 0' of str2 is not automatically allocated, and str2 is allocated next to str1, when reading str2, the content in str1 is automatically read without the ending character '\ 0, in this way, str2 truncates "ABCD" and reads str1 content in succession. The result of strlen (str2) is the total length of str1 + str2. |
| Str3 |
The length is easy to understand.
|
| Str4 |
Note that the NULL Character in str4 is between '5' and '1'. It is a null character rather than the ending character '\ 0', so the length of str4 is easy to understand.
|
| Str5 |
Because I explicitly add an ending character '\ 0' to the string, it will end from the first' \ 0' when reading or judging the length of the string, then the first '\ 0' will mislead you when accessing str5.
|
From Weizhi note (wiz)
String Length function strlen ()