Defying Array Indexing Convention
In a language like C, where object-oriented programming is considered heresy, arrays are one of the most important data structures. Arrays are indexed by non-negative integers, starting from zero. For example:
In the example above, accessing array x
at index 2
gives us 4
. That makes sense. Not really rocket science.
But why? What does it mean to access at index 2
? And what even is x
?
Oh I see, x
is in fact a pointer. x
points to the address of the array. In particular, it points to the address where the first element of the array is stored. We can see this by dereferencing x
:
Dereferencing x
gives us 3
, which is the first element of the array.
But wait, what if instead of the first element, we want to access the element at index 2
like we did above? Well then, we just add 2
to x
's address and dereference that:
That seems to work! Adding 2
to x
advances the pointer by two 4-byte addresses (in most systems anyway), which lands us on the third element of the array, 4
. In fact the conventional way of indexing arrays, i.e. x[i]
, is actually just syntactic sugar for *(x + i)
. They are equivalent.
Hold on there, isn't addition commutative though? In other words, x + 2
should be equivalent to 2 + x
. So I could just as easily do:
Interesting! Wait a minute, does that mean, instead of accessing x
at index 2
, we can also access 2
at index x
?
We most certainly can! No compilcation error, we get the output we expect. On first glance it does not make sense at all, but given a basic understanding of array indexing in C, it makes a lot of sense!
Disclaimer: This blog is purely informational and doesn't suggest you actually index arrays like this. Seriously. You'll give your fellow developers brain damage.