Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using negative number as array index

Tags:

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.

like image 333
Jishan Avatar asked Aug 29 '14 18:08

Jishan


1 Answers

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.

like image 85
Sergey Kalinichenko Avatar answered Oct 28 '22 16:10

Sergey Kalinichenko