As Joel points out in Stack Overflow podcast #34, in C Programming Language (aka: K & R), there is mention of this property of arrays in C: a[5] == 5[a]
Joel says that it's because of pointer arithmetic but I still don't understand. Why does a[5] == 5[a]
?
"a[5]" is the value that's 5 elements further from "a". The address of this element is "a + 5". This is equal to offset "a" from "5" elements at the beginning of the address space (5 + a).
(&array)[1] would be the next array of 16 integers, if there was one. If you do array[0] , the value you end up with is an integer, which you can't subscript again. array[1] is just the next integer.
Basically, “array” is a “pointer to the first element of array” but “&array” is a “pointer to whole array of 5 int”. Since “array” is pointer to int, addition of 1 resulted in an address with increment of 4 (assuming int size in your machine is 4 bytes).
Only square brackets([]) must be used for declaring an array.
The C standard defines the []
operator as follows:
a[b] == *(a + b)
Therefore a[5]
will evaluate to:
*(a + 5)
and 5[a]
will evaluate to:
*(5 + a)
a
is a pointer to the first element of the array. a[5]
is the value that's 5 elements further from a
, which is the same as *(a + 5)
, and from elementary school math we know those are equal (addition is commutative).
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