0

I was experimenting some stuff with pointers in my school today when i found that the following code would output

1
2
3
4
5
6
7
8
9

Here is the code:

int foo[10];
int i;
for (i = 0; i < 10; i++)
foo[i] = i;

for (i= 0; i < 10; i++)
printf("%d\n", i[foo]);

I have been looking for an explanation on the internet but I can't seem to find one.

Spikatrix
  • 19,653
  • 7
  • 38
  • 77
ouphi
  • 177
  • 1
  • 8

1 Answers1

0

This is because i[foo] is interpreted by your compiler as *(i + foo) which is the same than foo[i] ( *(foo +i) ). So your are printing the foo[i]'s Note that *(foo + i) does point to the correct address because of the pointer arithmetic system. When you add a number A to a pointer, your are actually adding A*sizeof(*your_pointer)

Valentin Mercier
  • 5,196
  • 3
  • 25
  • 50