Home >Backend Development >C++ >Why do `strlen` and `sizeof` give different results for pointer and array string initialization in C?
In C programming, the use of pointers and arrays to initialize strings can lead to unexpected disparities in the outputs of strlen and sizeof. Let's analyze this phenomenon by examining a specific example.
The code snippet 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>
produces the following output:
7 4 7 8
The variations arise due to the fundamental differences between pointers and arrays in their data type and object sizing.
Pointer (str1)
Array (str2)
To further illustrate these concepts, let's modify the code slightly:
<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>
This code will produce identical results for both str1 and str2 in terms of strlen: 7. However, sizeof(str1) will remain 4, representing the memory address, while sizeof(str2) will adjust to 8, still accounting for the null-terminated character.
Therefore, the key takeaway is to understand the distinct data types and sizing characteristics of pointers and arrays when working with strings in C programming.
The above is the detailed content of Why do `strlen` and `sizeof` give different results for pointer and array string initialization in C?. For more information, please follow other related articles on the PHP Chinese website!