We have a statement like- printf("Hello World"); Does printf append a null character after 'd' in the given string?
3 Answers
When you write
printf("xyz");
you are actually passing a string consisting of three characters and a null-terminator to printf.
printf("xyz");
// is equivalent to
static const char xyz[] = { 'x', 'y', 'z', 0 };
printf(xyz);
both printfs have the same effect: they write the characters x, y and z to the console. The null-terminator is not written.
Comments
Try this:
#include <stdio.h>
int main()
{
char string0[] = {'a', 'b', 'c'};
char string1[] = {'a', 'b', 'c','\0'};
printf("%s", string0);
puts("");
printf("%s", string1);
return 0;
}
If you are lucky enough, you will see something like:
abc$#r4%&^3
abc
printf() does not append a '\0' to the string. It doesn't make any change to the string to be output, because its task is to "print", rather than "modify". Instead, it is the null characters that tell printf() where is the end of the strings.
Comments
When a string is defined e.g. "hello world" it is null terminated by default. printf does nothing related to null terminate expect its own print processing. It only accepts char* as input. In your example "Hello World" is temp string and null terminated already before passed to printf. If the passed string is not null terminated then the behavior is undefined.
printfdoes not do that in any case .