ninja ninja - 3 years ago 156
C Question

Retrieval of values in reverse order using pointers

I understand working of *(p+i), but, what actually is happening at memory level when retrieving values with *(p-i) or p[-i] through printf() function ?

#include <stdio.h>

int main() {
int i, arr[5] = {1, 2, 3, 4, 5}, *p;
p = &arr[4];
for (i = 0; i < 5; i++)
printf("%d\t%d\t", *(p - i), p[-i]);
// why does this prints in reverse order?
return 0;
}

Answer Source

It's simple, *(p - i) and p[-i] are exactly the same with different syntax. It's interesting that you can also write, -i[p] with exactly the same meaning *(p - i).

It prints in the reverse order because you start at arr[4] and then subtract i from the pointer, which subtracts 0, 1, 2 one by one until it reaches 4, so it prints p[4], p[3], p[2], p[1], p[0] which is the array arr from the last element to the first.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download