I came along a competitive question that asks the output of the following:
#include <stdio.h> int main() { int a[] = {0,1,2,3,4}; int i, *ptr; for(ptr = a+4, i=0; i <=4; i++) printf("%d", ptr[-i]); return 0; } I did read this topic: Are negative array indexes allowed in C? However it was unclear to me how the -ve symbol generates the array in the reverse order, ie. 4, 3, 2, 1, 0.
First, recall that in C the expression ptr[index] means the same thing as *(ptr+index).
Now let's look at your expression again: ptr is set to a+4 before the loop; then you apply -i index to it. Therefore, the equivalent pointer arithmetic expression would be as follows:
printf("%d", *(a+4-i)); This expression iterates the array backwards, producing the results that you see.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With