C array pointer increment

Okay, you have some issues with your program but i’ll try my best…

first, your issue lies with th line ptr1 = (ptr+=sizeof(int))[-2]; I can’t understand what you expect it will do but what it actually does is ptr = ptr[4]; ptr1 = ptr[-2]

I tried to put out some debugging info to be more clear on the matter,

strings mapped in memory

0x400624 ant
0x400628 bat
0x40062c cat
0x400630 dog
0x400634 egg
0x400638 fly

to verify sizeof(int) is 4

at the start of function

*ptr - 0x400624 - "ant"

after your assignment to ptr1

*ptr - 0x400634 - "egg"
ptr1 = 0x40062c - "cat"

as you can see

  1. ptr now points to “egg” as the actual assignment to it was ptr = ptr[4]
  2. ptr1 is now pointing to “cat” as it is assigned ptr1 = ptr[-2]

You should readup on two things: “C order of evaluation” and also “pointer arithmatics”

Hope this helps…

Leave a Comment