Home > Backend Development > C++ > body text

Why do `strlen` and `sizeof` produce different results for pointer-based and array-based strings in C?

Patricia Arquette
Release: 2024-11-02 06:37:02
Original
185 people have browsed it

Why do `strlen` and `sizeof` produce different results for pointer-based and array-based strings in C?

Distinct Outputs in String Length and Size Calculations for Pointer-Based and Array-Based String Initialization

Understanding the Results

When creating a pointer-based string str1 and an array-based string str2 with the same value, the functions strlen and sizeof produce different results. Specifically, for the declarations:

<code class="c">char *str1 = "Sanjeev";
char str2[] = "Sanjeev";</code>
Copy after login

strlen returns 7 for both str1 and str2 since it measures the length of the character sequence, excluding the null-terminator (

The above is the detailed content of Why do `strlen` and `sizeof` produce different results for pointer-based and array-based strings 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!