-1

I'm reading Head First C and going well so far but I'm having trouble with this example -

int doses[] = {1, 3, 2, 1000};
printf("Issue dose %i", 3[doses]);

Result = "Issue dose 1000"

I know what this does, it accesses index 3 of the doses array. More technically my understanding is that it adds the size of three integers to the pointer address for the first element in the array ( the doses variable )

The book explains that it works because

doses[3] == *(doses + 3) == *(3 + doses) == 3[doses]

I'm with it up until that final jump between *(3 + doses) == 3[doses]. Given that doses[3] is easy for me to grasp maybe I'm not understanding the significance of the [] correctly?

LiamRyan
  • 1,892
  • 4
  • 32
  • 61
  • For the second and third expressions in your final "code" line, isn't it obvious that `*(doses + 3) == *(3 + doses)`? For the first and last expressions, you wrote above that you already understand that `doses[3] == 3[doses]`. Please remember that pointer arithmetic works the same way as the equivalent array indexing. Adding 3 to a pointer under the hood adds `3*sizeof`its type. – Weather Vane Jan 14 '17 at 20:01
  • Yes it was obvious up until it jumped to the 3[doses] because I had not seen the C standard for the [] operator which is why I asked the question. Apologies for the duplicate but it's not a very easy thing to search for I tried several variations – LiamRyan Jan 14 '17 at 20:16

1 Answers1

2

The C standard defines the [] operator as follows:

doses[3] == *(doses + 3)

Therefore doses[3] will evaluate to:

*(doses + 3)
and 3[doses] will evaluate to:

*(3 + doses)

Hope it helped you ;)

Razvan Alex
  • 1,706
  • 2
  • 18
  • 21