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
  • 20,225
  • 7
  • 37
  • 83
ouphi
  • 232
  • 2
  • 9

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,256
  • 3
  • 26
  • 50