"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-11-16
Browse:729

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:

char *str1 = "Sanjeev";
char str2[] = "Sanjeev";

strlen returns 7 for both str1 and str2 since it measures the length of the character sequence, excluding the null-terminator (\0) at the end.

However, sizeof yields different values:

  • sizeof(str1) returns 4 because it evaluates the size of the pointer variable, which is typically 4 bytes (32-bit systems).
  • sizeof(str2) returns 8 because it determines the size of the array, which includes the null-terminator, resulting in 8 bytes (7 characters 1 null-terminator).

The Underlying Difference: Data Type versus Memory Allocation

sizeof measures the size of the data type, while strlen measures the length of the character sequence. In the case of str1, it is a pointer to a char, so sizeof returns the size of the pointer. For str2, it is an array of chars, so sizeof returns the size of the entire array, including the null-terminator.

A Closer Look

To demonstrate the distinction better, consider:

char str2[8];
strncpy(str2, "Sanjeev", 7);
char *str1 = str2;

Now, both str1 and str2 point to the same array. Their strlen values are 7, but their sizeof values differ:

  • sizeof(str1) is 4 (pointer size)
  • sizeof(str2) is 8 (array size with null-terminator)

This exemplifies how the size evaluation depends on the underlying data structure.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3