In an introductory course of C, I have learned that while storing the strings are stored with null character \0
at the end of it. But what if I wanted to print a string, say printf("hello")
although I've found that that it doesn't end with \0
by following statement
printf("%d", printf("hello")); Output: 5
but this seem to be inconsistent, as far I know that variable like strings get stored in main memory and I guess while printing something it might also be stored in main memory, then why the difference?
"printf" is the name of one of the main C output functions, and stands for "print formatted". printf format strings are complementary to scanf format strings, which provide formatted input (lexing aka. parsing).
\0 is zero character. In C it is mostly used to indicate the termination of a character string.
If you want to print a \ you need to escape that (since \ is a special character itself). Put \\ in your string to print \ . If you want to print \\ your format string has to be \\\\ (i.e. escape both \ s).
The escape sequence \n means newline. When a newline appears in the string output by a printf, the newline causes the cursor to position to the beginning of the next line on the screen.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With