Home  >  Article  >  Backend Development  >  Why do `strlen` and `sizeof` produce different results for pointer-based and array-based strings in C?

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

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 06:37:02186browse

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>

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!

Statement:
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