First,strlenis a function,sizeofis an operator, and the result type obtained by both issize_t, that is,unsigned inttype. Most compilers, at compile time, have alreadysizeofcalculated, whilestrlenthe result can only be calculated at runtime.
For the following statement:
char *str1 = "asdfgh";
char str2[] = "asdfgh";
char str3[8] = {'a', 's', 'd'};
char str4[] = "as\0df";
The execution result is:
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. sizeof obtains the address space occupied by the pointer, which corresponds to 4 bytes in a 32-bit operating system, so the result is 4; strlen returns the length of the string, and stops when it encounters\0ends,\0itself is not counted, so the result is 6.
str2 is a character array, its size is determined by the string constant "asdfgh". sizeof obtains the size of the memory space occupied by the array, including the ending\0, so the result is 7; strlen similarly returns 6.str3 is also a character array, but its size is determined as 8, so sizeof gives the result 8; strlen counts\0the number of all characters before it, which is 3;
str4 is a constant character array, sizeof gets the total number of characters, i.e., 6; strlen counts up to\0the end, so it returns 2;
In summary, sizeof calculates the size of a variable, while strlen calculates the length of a string. The former is not affected by the character\0influence, while the latter uses\0as the basis for determining length.
Original address: https://blog.csdn.net/shudaxia123/article/details/47753505