Precautions for Obtaining String Length Using strlen and sizeof
Category Programming Techniques
Firstly, strlen is a function, and sizeof is an operator for size calculation, both yielding a result of type size_t, which is equivalent to unsigned int
. Most compilers calculate the value of sizeof at compile time, while the result of strlen is determined at runtime.
For the following statements:
char *str1 = "asdfgh";
char str2[] = "asdfgh";
char str3[8] = {'a', 's', 'd'};
char str4[] = "as\0df";
The execution results are:
sizeof(str1) = 4; strlen(str1) = 6;
sizeof(str2) = 7; strlen(str2) = 6;
sizeof(str3) = 8; strlen(str3) = 3;
sizeof(str4) = 6; strlen(str4) = 2;
str1 is a character pointer variable, and sizeof gets the address space occupied by this pointer, which corresponds to 4 bytes on a 32-bit operating system, hence the result is 4; strlen returns the length of the string, ending at \0
, and \0
itself is not counted, so the result is 6. str2 is a character array, and sizeof gets the total number of characters, which is 7; strlen returns 6 for the same reason.
str3 is also a character array, but its size is fixed at 8, so the result of sizeof is 8; strlen counts all characters before \0
, which is 3.
str4 is a constant character array, and sizeof gets the total number of characters, which is 6; strlen counts until \0
ends, thus returning 2.
In summary, sizeof calculates the size of a variable, while strlen calculates the length of a string, the former is unaffected by the character \0
, and the latter uses \0
as the basis for determining length.
>
Original article link: https://blog.csdn.net/shudaxia123/article/details/47753505
**Share my notes
-
-
-