3

Explain how sizeof determines the length of the string.

#include<stdio.h>

int main()
{
    char str[] = "Sasindar\0Baby\0";
    printf("%d\n", sizeof(str));
    return 0;
}
XOR
  • 314
  • 5
  • 11
  • 1
    What is your question? What results does it give, and what do you expect? – Glorfindel Aug 01 '15 at 09:34
  • I'm voting to close this question as off-topic because easily Googleable and almost certainly duped. – Martin James Aug 01 '15 at 11:04
  • possible duplicate of [difference between sizeof and strlen in c](http://stackoverflow.com/questions/8590332/difference-between-sizeof-and-strlen-in-c) – r3mainer Aug 01 '15 at 11:16

1 Answers1

6

sizeof does not determine the length of the string. It determines how many bytes a structure takes in memory.

In your case, the structure is str, an array of bytes. The compiler knows how many bytes, including the two trailing '\0's, was placed into the array, so it produces the proper size at compile time. sizeof has no idea that str is a null-terminated C string, so it produces 15.

This is in contrast to strlen, which interprets your string as a C string, and returns the count of characters before the first '\0'.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523