'\0' and printf() in C
In C all literal strings are really arrays of characters, which include the null-terminator.
However, the null terminator is not counted in the length of a string (literal or not), and it's not printed. Printing stops when the null terminator is found.
printf
returns the number of the characters printed. '\0'
is not printed - it just signals that the are no more chars in this string. It is not counted towards the string length as well
int main()
{
char string[] = "hello";
printf("szieof(string) = %zu, strlen(string) = %zu\n", sizeof(string), strlen(string));
}
https://godbolt.org/z/wYn33e
sizeof(string) = 6, strlen(string) = 5
Your assumption is wrong. Your string indeed ends with a \0
.
It contains of 5 characters h
, e
, l
, l
, o
and the 0 character.
What the "inner" print()
call outputs is the number of characters that were printed, and that's 5.
The null byte marks the end of a string. It isn't counted in the length of the string and isn't printed when a string is printed with printf
. Basically, the null byte tells functions that do string manipulation when to stop.
Where you will see a difference is if you create a char
array initialized with a string. Using the sizeof
operator will reflect the size of the array including the null byte. For example:
char str[] = "hello";
printf("len=%zu\n", strlen(str)); // prints 5
printf("size=%zu\n", sizeof(str)); // prints 6