Home >Backend Development >C++ >Why Do `strlen` and `sizeof` Produce Different Outputs for Pointers and Arrays in C?

Why Do `strlen` and `sizeof` Produce Different Outputs for Pointers and Arrays in C?

DDD
DDDOriginal
2024-11-01 03:03:021055browse

Why Do `strlen` and `sizeof` Produce Different Outputs for Pointers and Arrays in C?

Different Outputs from Strlen and Sizedof Due to Pointer and Array Initialization

In C programming, sizeof and strlen functions provide information about the size and length of data types, respectively. However, when dealing with pointers and arrays, the outputs of these functions can differ, leading to confusion.

Consider the following example:

<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 from this code is:

7 4
7 8

Explanation:

  • Str1 (Pointer Initialization): str1 is initialized as a pointer to the string literal "Sanjeev." sizeof(str1) gives the size of a pointer, which is 4 bytes in most architectures. On the other hand, strlen(str1) returns the length of the string pointed to by str1, which is 7 (excluding the null terminator '

The above is the detailed content of Why Do `strlen` and `sizeof` Produce Different Outputs for Pointers and Arrays 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