Home > Backend Development > C++ > body text

Why do `strlen` and `sizeof` give different results for pointer and array string initialization in C?

Mary-Kate Olsen
Release: 2024-11-01 00:42:28
Original
166 people have browsed it

Why do `strlen` and `sizeof` give different results for pointer and array string initialization in C?

Pointer vs. Array String Initialization: Discrepancies in strlen and sizeof

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>
Copy after login

produces the following output:

7 4
7 8
Copy after login

The variations arise due to the fundamental differences between pointers and arrays in their data type and object sizing.

Pointer (str1)

  • strlen(str1) returns 7, representing the length of the string pointed to by str1 (excluding the null terminator).
  • sizeof(str1) returns 4 because str1 is a pointer variable with a 4-byte memory address (32-bit system).

Array (str2)

  • strlen(str2) returns 7 as well, considering the length of the string in the array.
  • sizeof(str2) returns 8 because str2 is an array containing eight characters, including the null terminator.

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!