Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing arrays by index[array] in C and C++

There is this little trick question that some interviewers like to ask for whatever reason:

int arr[] = {1, 2, 3}; 2[arr] = 5; // does this line compile? assert(arr[2] == 5); // does this assertion fail? 

From what I can understand, a[b] gets converted to *(a + b) and since addition is commutative, it doesn't really matter their order, so 2[a] is really *(2 + a) and that works fine.

Is this guaranteed to work by C and/or C++'s specs?

like image 474
NullUserException Avatar asked Feb 22 '11 02:02

NullUserException


People also ask

How do you access an array index?

To access an individual element of an array, use the name of the array name followed by the index of the element in square brackets. Array indices start at 0 and end at size-1: array_name[index]; accesses the index'th element of array_name starting at zero.

How are arrays indexed in C?

Arrays in C are indexed starting at 0, as opposed to starting at 1. The first element of the array above is point[0]. The index to the last value in the array is the array size minus one. In the example above the subscripts run from 0 through 5.

How can we access the elements of array in C?

Array elements are accessed by using an integer index. Array index starts with 0 and goes till the size of the array minus 1. The name of the array is also a pointer to the first element of the array.

Can you access an element in an array by using its index?

You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.


1 Answers

Yes. 6.5.2.1 paragraph 1 (C99 standard) describes the arguments to the [] operator:

One of the expressions shall have type "pointer to object type", the other expression shall have integer type, and the result has type "type".

6.5.2.1 paragraph 2 (emphasis added):

A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).

It says nothing requiring the order of the arguments to [] to be sane.

like image 106
Chris Lutz Avatar answered Oct 09 '22 03:10

Chris Lutz