+ 1

what does pointer index -1 means ? Help me understand output of code

Hello Please refer below code: https://code.sololearn.com/cIoGSThWA599 I understand that initially ptr is referring to index 0 of array, Then ptr +=2; move ptr reference to two more elements. but what does ptr[-1] and why output is 11?

9th Jun 2020, 5:05 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
5 odpowiedzi
+ 4
`arr[i]` is the same as `*(arr + i)` So after you add 2 to ptr, it points to the third element. Therefor ptr[-1] is the second element, 6. So ptr == a + 2 + 6!
9th Jun 2020, 5:19 PM
Schindlabua
Schindlabua - avatar
+ 3
int* ptr = a; You point to the first element. ptr +=2; You increment the pointer by 2 and now it is at 7. ptr[-1]; Your pointer takes a step back and it is now at 6. ptr += ptr[-1] is same as ptr += 6 Your pointer will now move to 11. Also *(ptr), *(ptr+0), ptr[0] are all the same.
9th Jun 2020, 6:42 PM
Avinesh
Avinesh - avatar
+ 1
Yo...thanks Avinesh ... Thanks Schindlabua
9th Jun 2020, 7:32 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
I am still confused.... By doing arithmetic , we can move left or right but not adding values i.e. 5+6 So just doing something on index means we are moving pointer p accross the array index...isn't it? Would request to elaborate plz
9th Jun 2020, 6:20 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Ptr[-1] means second element's value that is 6 and that we added to p not values
9th Jun 2020, 6:22 PM
Ketan Lalcheta
Ketan Lalcheta - avatar