Martin Nyaga

Bizarre Array Manipulation in C

February 22nd, 2017

Of all the strange behaviours I've come accross while trying to gain a working knowledge of C, this must be the most bizarre one yet.

Imagine you want to print all the numbers in a n array in C.

int main(){
  int arr[] = {1, 2, 3,4, 5};
  int i;

  for(i = 0; i < 5; i++){
    printf("%d\n", arr[i]);

  return 0;

Works as you'd expect.

Now in C, arrays are really just pointers to an allocated block of memory. So arr, is a pointer to a block. The square bracket notation, arr[i] is just syntactic sugar for dereferencing a pointer. So arr[i] above is equivalent to:

printf("%d\n", *(arr + i));
// *(arr + i) => The value at the address given by (arr + i)

Now, because this operation is basic arithmetic, it means you should be able to access the same values using *(i + arr) . Fairly obvious, and it works as you'd expect.

printf("%d\n", *(i + arr));

Here's where things get a bit crazy.

If arr[i] is equivalent to *(arr + i) , and the square brackets are just syntactic sugar, then *(i + arr) should be the same as i[arr] . And so arr[i] and i[arr] are practically the same thing.

printf("%d\n", i[arr]);
// Absolutely insane

And it actually works.