int main (void)
{
char c[] = "KATEWINCE";
char *p =c;
printf("%s", p+p[3]-p[1]) ;
return (0);
}
The output is WINCE but I don't get how the code is working, please explain.
int main (void)
{
char c[] = "KATEWINCE";
char *p =c;
printf("%s", p+p[3]-p[1]) ;
return (0);
}
The output is WINCE but I don't get how the code is working, please explain.
You assigned 0x45 to c[3]
/p[3]
.[1]
You assigned 0x41 to c[1]
/p[1]
.[1]
So p + p[3] - p[1]
is equivalent to p + 0x45 - 0x41
.
This attempts to advance p
by 0x45 elements. This is undefined behaviour. You can advance a pointer to the position immediately following the object to which it points, but no further. c
is simply not that large.
But let's say c
was far larger. You would see the same result as you posted here.
p
is advanced by 0x45 elements, then reversed by 0x41 elements. The net result is that p
is advanced by 4 elements. And that's exactly what we see.