Recently I have seen a code in which a string was being sorted, and \0
(since it has smallest ASCII code) came first of the string.
But using format specifier %c
the true sorted string was printed, but I checked with %s
and nothing was printed.
So here is my question, if I add a \0
in a string (while I have valid value in my string after terminator), could I access those values with something like %c
, is it safe? And will this answer always or it just answered because of UB?
Here is an example:
int main()
{
char a[8]="abcdefg";
char b[8];
for (int i = 0; i < 8; i++)
{
b[7-i] = a[i];
}
for (int i = 0; i < 8; i++)
printf("%c ", b[i]);
printf("%s", b);
}
In above example printf("%c ", b[i]);
prints the hole string , even after \0
.
In second one printf("%s", b);
nothing is printed?
Actually I want to know if using first printf
is true and legal?