The expression a[i]
is the same as i[a]
in C due to the way array subscripting is implemented in the language. This equivalence stems from the pointer arithmetic and array indexing rules in C.
In C, an array name is essentially a pointer to the first element of the array. So, a
is a pointer to a[0]
. The expression a[i]
is defined as *(a + i)
. This means that when we use a[i]
, it is interpreted as the value at the memory address a
moved i
elements forward. Since addition is commutative (*(a + i)
is equivalent to *(i + a)
. Therefore, a[i]
is the same as *(i + a)
, which is what i[a]
essentially represents.
Let’s look at a code example to demonstrate this concept.
#include <stdio.h>#define ARRAY_SIZE 10int main() {int i, a[ARRAY_SIZE];// populate array valuesfor (i = 0; i < ARRAY_SIZE; i++) {a[i] = (i+1)*10;}// print a[i] and i[a]for (i = 0; i < ARRAY_SIZE; i++) {printf("%d\t%d\n", a[i], i[a]);}return 0;}
In the code above, we initialize an array a
with size ARRAY_SIZE
(10
). We populate the array’s values using a loop. Finally, we print the array’s values using both a[i]
indexing and i[a]
indexing to compare the results.
Let’s illustrate this with an example using dummy values and memory addresses. Assume we have an array a
with 10 integers, and we’ll consider the case for a[2]
and 2[a]
.
Let’s say our array a
looks like this, with each element being an integer:
a = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Let’s assume the starting address of this array (address of a[0]
) is 0x100
. In C, integers are commonly 4 bytes (this can vary based on the system, but we’ll use 4 bytes for this example).
The memory layout would look something like this:
Address Value-----------------0x100 10 (a[0])0x104 20 (a[1])0x108 30 (a[2])0x10C 40 (a[3])... ...
Now, let’s analyze a[2]
and 2[a]
.
a[2]
: This is the standard way of accessing the third element in the array. It translates to *(a + 2)
. Here a
is a pointer to 0x100
, and adding two means moving forward by two integer spaces (8 bytes since each integer is 4 bytes). So, a + 2
points to the memory address 0x100 + 8
, which equals 0x108
. *(a + 2)
dereferences this address, giving us the value stored there, which is 30
.
2[a]
: This is an unconventional but valid way of accessing the same element. It translates to *(2 + a)
. Since addition is commutative, 2 + a
is the same as a + 2
, so this also points to 0x108
. Dereferencing this (*(2 + a)
) also gives us 30
.
Therefore, both a[2]
and 2[a]
access the memory address 0x108
and yield the same value, 30
.
Free Resources