Home >Backend Development >C++ >Why do `strlen()` and `sizeof()` return different results for string initialization in C?
Understanding the Discrepancy in strlen() and sizeof() Results for String Initialization
In C programming, there is often a discrepancy between the results of strlen() and sizeof() when dealing with pointers and arrays initialized to strings. This seemingly contradictory behavior can be explained by understanding the nature of pointers and arrays.
Consider the example code provided:
<code class="c">char *str1 = "Sanjeev"; char str2[] = "Sanjeev"; printf("%d %d\n", strlen(str1), sizeof(str1)); printf("%d %d\n", strlen(str2), sizeof(str2));</code>
The output for this code is:
7 4 7 8
The different results for strlen() and sizeof() stem from the fact that str1 is a pointer to a string while str2 is an array of characters.
Sizeof() vs. Strlen() for Pointers
sizeof() determines the size of the data type in bytes. In the case of a char pointer, such as str1, sizeof returns 4 on a 32-bit system (8 on a 64-bit system) because a pointer takes up 4 (or 8) bytes of memory. However, strlen returns the length of the string pointed to by the character pointer. Since the string "Sanjeev" has 7 characters, strlen returns 7.
Sizeof() vs. Strlen() for Arrays
In contrast, str2 is an array of characters. sizeof(str2) returns the size of the entire array, which includes both the characters and the null-terminator (added automatically to all C strings). Hence, sizeof(str2) returns 8 (the number of characters in "Sanjeev" plus the null-terminator). strlen(str2) also returns 7, which is the length of the string excluding the null-terminator.
Additional Considerations
To further illustrate the difference, consider the following code:
<code class="c">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));</code>
In this case, str1 is now a pointer that points to the beginning of the character array str2. As before, strlen(str1) returns 7 and sizeof(str1) returns 4. However, strlen(str2) also returns 7, while sizeof(str2) still returns 8. This is because str2 remains an array, and the size of an array is determined by the number of elements it contains, regardless of whether they are actually used.
The above is the detailed content of Why do `strlen()` and `sizeof()` return different results for string initialization in C?. For more information, please follow other related articles on the PHP Chinese website!