A string in C is a sequence of characters followed by a NUL character, which is '\0'
. There is no separate "length" field.
When a string appears as a literal, such as "hello"
, what actually gets stored in memory is:
'h', 'e', 'l', 'l', 'o', '\0'
So you can see that if your string itself contains a '\0'
, as far as any of the C standard library functions are concerned, that's the end of the string.
Once printf
see the first '\0'
in your string, it stops printing and returns, because that's the end of the format string. printf
has no way of knowing that there's another string after the '\0'
. Maybe there is--or maybe there's just random other program data in memory after that point. It can't tell the difference.
If you want to actually print the '\0'
characters, then you need to have some other way to track the "real" length of the string and use a function that accepts that length as a parameter. Alternately you could add the '\0'
characters during the formatting process by specifying %c
in the format string and passing 0
as the character value.