# 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?
# 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?
This is what is happening:
"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.sizeof when applied to an array yields its size in bytes. 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++
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.
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.
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