Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With arrays, why is it the case that a[5] == 5[a]?

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]?

like image 526
Dinah Avatar asked Dec 19 '08 17:12

Dinah


People also ask

Why in C language is it the case that 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).

What does &array mean in C?

(&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.

What's difference between array and &array for int array 5?

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).

Which is the proper way to declare an array?

Only square brackets([]) must be used for declaring an array.


1 Answers

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).

like image 189
mmx Avatar answered Oct 11 '22 06:10

mmx