Different answers from strlen and sizeof for Pointer & Array based init of String [duplicate]
In the C programming language, when declaring an array and a pointer to a string, different outputs can be obtained using the 'strlen' and 'sizeof' functions. Understanding this discrepancy is crucial for effective memory management and data handling.
To illustrate this difference, consider the following code snippet:
char *str1 = "Sanjeev"; char str2[] = "Sanjeev"; printf("%d %d\n",strlen(str1),sizeof(str1)); printf("%d %d\n",strlen(str2),sizeof(str2));
The output produced will be:
7 4 7 8
The 'strlen' function returns the number of characters in the string, excluding the null terminator. In both cases, the string contains 7 characters. The 'sizeof' function, on the other hand, returns the size of the data type in memory.
For 'str1', a pointer, 'sizeof(str1)' returns the size of the pointer variable itself, which is typically 4 bytes on most systems. This is because 'str1' is not an array but merely a pointer to the string "Sanjeev."
In contrast, 'str2' is an array of characters. 'sizeof(str2)' returns the size of the entire array, including the null terminator. As a result, it outputs 8 bytes: 7 bytes for the characters and 1 byte for the null terminator.
To further understand this concept, consider the following modified code:
char str2[8]; strncpy(str2, "Sanjeev", 7); char *str1 = str2; printf("%d %d\n",strlen(str1),sizeof(str1)); printf("%d %d\n",strlen(str2),sizeof(str2));
This time, the output will be:
7 4 7 8
Even though 'str1' and 'str2' refer to the same string, the 'sizeof' outputs remain the same. This is because 'str1' is still a pointer, and 'str2' remains an array. The 'strlen' output remains 7 for both, as it only counts the characters in the string.
The above is the detailed content of Why do `strlen` and `sizeof` return different values for pointer and array-based string initialization in C?. For more information, please follow other related articles on the PHP Chinese website!