-1
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.

  • Assuming ASCII encoding of your characters, look up the values ASCII values of the characters `p[3]` and `p[1]`. Then it's plain *pointer arithmetic*. – Some programmer dude Jun 27 '21 at 10:34
  • 1
    I also recommend you take some squared paper, write each letter in the array `c` in its own square, and then make an arrow pointing to the first character. This arrow is the pointer `p`. Then add `p[3]` squares and make the arrow point to that square. Then subtract `p[1]` and again redraw the arrow. That might help you understand what's going on. – Some programmer dude Jun 27 '21 at 10:36
  • 1
    `p+p[3]-p[1]` is `p + 'E' - 'A'` and assuming the letter coding is sequential that is `p + 4` which is where `"WINCE"` begins. – Weather Vane Jun 27 '21 at 11:10
  • 1
    Is this an assignment you were given in a class you're taking? It's a terrible, meaningless problem. Pointer arithmetic is perfectly reasonable; we do it all the time. It's occasionally meaningful (and it's not wrong) to subtract the values of two characters. But it's very hard to think of a realistic reason why you would subtract the values of two characters, then use the difference to do pointer arithmetic like this. If you understand why `printf("%s", p+4)` prints "WINCE", you understand the essential property of pointer arithmetic. The character subtraction is just obfuscation. – Steve Summit Jun 27 '21 at 11:50
  • Yes I got it... Thanks for help, and yes it was a part of assignment. – Yash Jiwani Jun 27 '21 at 20:36

1 Answers1

1

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.


  1. Assuming an ASCII-based machine.
ikegami
  • 367,544
  • 15
  • 269
  • 518