char *x = "world";
x = &x[6];
printf("%s", x);
Hi I can't understand why the above code is outputting the first argument in the printf statement. If I change it to printf("f%s",x);
it outputs "ff%s" why does it output ff twice?
Thanks
char *x = "world";
x = &x[6];
printf("%s", x);
Hi I can't understand why the above code is outputting the first argument in the printf statement. If I change it to printf("f%s",x);
it outputs "ff%s" why does it output ff twice?
Thanks
Because you are reading beyond the array boundary. Your array is of length 6 (0-5) and you're accessing 6th member (your last available is 5th). That is an undefined operation and will do unpredictable things like print out portion of your printf statement.
Coincidence. It is undefined behaviour. Your are addressing a wrong memory.
&x[6]
is equivalent to &(*(x+6))
. I.e. you are addressing just after the string's end value which is '\0'
and it seems that the string "s%"
starts there.
Because the format string is stored after "world"
immediately in the read only data section, so after
x = &x[6];
now x
points to the format string.
That's just a coincidence, in practice it should be not possible to predict the output of that program, but it turns out there is a way to arrange the program in memory and the knowledge of that way, allows someone to write such an interesting code.
This
char *x = "";
x = &x[1];
would not cause the same behavior for example, but anything with more than 0
characters will.