-1

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; 
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
ninja
  • 3
  • 4

2 Answers2

1

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.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
0

You have assigned last element address in the pointer and subtracting address one by one and hence it prints in reverse order

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • Assume your integer takes 4bytes each, and let 1000 be the memory location of arr[0] then below are the memory allocation 1000=> arr[0] 1004=> arr[1] 1008=> arr[2] 1012=> arr[3] 1016=> arr[4] Now when you allocated pointer to arr[4], it points to the location 1016...and now you decrease it one by one, which means decreasing 4 bytes at a time – Akash Deep Sharma Jul 31 '17 at 11:32
  • got it man !! thnx – ninja Jul 31 '17 at 14:12
  • hi @ninja, please mark this answer useful by voting UP arrow if it was :-) – Akash Deep Sharma Aug 01 '17 at 04:58