0
# include <stdio.h>
int main()
{
        int a = sizeof("string");
        printf("%d", a );
        return 0;
}

The above code prints 7 as the output while the length of string is only 6. Could someone please explain?

Karan Bansal
  • 1,314
  • 1
  • 11
  • 16

5 Answers5

11

This is what is happening:

  • The string literal "string" is an array of (const) char, including a null-terminator character, i.e. {'s', 't', 'r', 'i', 'n', 'g', '\0'}. In your example, said array has 7 elements.
  • The operator sizeof when applied to an array yields its size in bytes.
  • The size of an array is the sum of the size of each of its elements.
  • The size of one char is 1.

So, you get the number of chars explicit in the literal, plus a null-terminator.

This behaviour is the same in both C and C++

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
4

All strings in c, even the ones you write like "string" are terminated with a null byte '\0'.

The expression "string" in c or c++ code is considered a string literal, that means a char array that looks like this: {'s','t','r','i','n','g','\0'}. In c and c++ all strings must be terminated by a null byte in memory, otherwise functions cannot identify their end.

This is, by the way, also why you must add 1 character when calculating lenght of character arrays in c code to account for the null byte. So if you want to store "string" in a character array that you declare, you would have to do char array[7]; using 6 here would lead to undefined behaviour.

Magisch
  • 7,312
  • 9
  • 36
  • 52
2

The length of the string is 6 and the null character is also added by default when we specify the string in "". So it prints 7.

2

Strings are null-terminated and stored as an array containing the characters and terminated with a null character ('\0', called NUL in ASCII). So you have:

s | t | r | i | n | g | \0 | 
                         ^-- 7th char
Sadique
  • 22,572
  • 7
  • 65
  • 91
1

Because "string" is implicitly adding a '\0' character.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190