I'm going through an exercise book on C and came across the statement
printf("%c", "\n");
Which when run in a console still works but displays the "$" symbol.
Why did this statement not crash the console like
printf("%s", '\n');
does?
I'm going through an exercise book on C and came across the statement
printf("%c", "\n");
Which when run in a console still works but displays the "$" symbol.
Why did this statement not crash the console like
printf("%s", '\n');
does?
a double quoted string like that produces a value of a pointer to char
(aka char*
), while the single quote produce a value that's a character (using the ASCII value of whats in the quotes. On some compilers you can stack multiple characters into the single quotes.
printf("%c", *("\n") );
would print your linefeed, as the *
operator would dereference the pointer
( You could probably do *"\n"
, I just tend to be conservative in writing expressions)
printf("%s", '\n');
crashes because %s
expects a pointer, and a linefeed cast into a pointer is pointing off in the weeds and most likely causes an invalid memory access
It will invoke undefined behavior by passing data having wrong type. It just happened not to crash.
In some implementation, the pointer converted from the string literal is passed as an argument. Unlike %s
, which will interpret the argument as pointer and go to read thete, %c
will just take the argument as a number and print it, so it has less chance to crash.
Because %s
expects a NUL
terminated string where %c
only wants a char. The string will read past the end of your buffer (the single char) looking for that NUL
and quite likely cause a memory exception. Or not - hence undefined behavior.
Only the latter statement asked the implementation to dereference an invalid pointer. An invalid value will typically show as garbage. But most possible memory location values are inaccessible and attempting to access them will cause a crash on modern operating systems.
%s prints until it reaches a '\0' because \n has no escape it will read into memory. "%c" only needs a char