+7

Are these just alternatives or is there a difference?

This little program is printing the same element of an two-dimensional array but using two different ways to specify which one. int main() { int arrSample[][2] = {{1,2},{3,4}}; cout << arrSample[1][0] << endl; // common way cout << 0[arrSample[1]] << endl; // alternatively return 0; } Or does it make any difference I don't know yet?

2/10/2019 6:47:18 AM

Michael Sander

2 Answers

New Answer

+11

Very, very interesting... In C/C++, the notation of: x[y] is equivalent to *(x+y) This means that for an array arr, and n as the index, arr[n] is equivalent to n[arr], since *(arr+n) and *(n+arr) returns the same value. The index of an array element you wish to access can actually be written outside the brackets, with the array identifier inside the brackets. They are essentially one and the same, although the norm is to write it as arr[n] instead of n[arr]. Further reading: https://stackoverflow.com/questions/381542/with-arrays-why-is-it-the-case-that-a5-5a

+1

@Hatsy Rei: Think I got it. Thank you very much. 🤓