+ 2

Can you please help me understand, why is the answer 5?

Code: Int mat [2][2]={{1,2}, {3,5}}; cout <<1[mat[1]];

30th Jun 2019, 4:48 AM
Jhozmer A. RamĂ­rez P.
Jhozmer A. RamĂ­rez P. - avatar
2 Answers
+ 2
That's because what actually happens behind an array subscription is simple pointer arithmetic. For example, the elements of one-dimensional array `int a[2]` are accessible as a[0], a[1] also, through the pointer arithmetic, it will be *(a + 0), *(a + 1) Since addition has commutative property, the following are also valid operations *(0 + a), *(1 + a) so are 0[a], 1[a]. That means arrays with higher dimensionality also follow the same rule. Here is the illustration of other variants for accessing individual elements of `mat` array. int main() { int mat [2][2] = { {1,2}, {3,5} }; cout << mat[1][1] << endl; // regular access using bracket cout << *(mat[1] + 1) << endl; // access using partial pointer arithmetic cout << *(*(mat + 1) + 1) << endl; // access using full pointer arithmetic cout << 1[mat [1]] << endl; // access using commutative property of pointer arithmetic cout << *(1 + mat[1]) << endl; cout << *(1 + *(mat + 1)) << endl; cout << 1[mat][1] << endl; // access using the same property cout << *(1 + 1[mat]) << endl; cout << *(1 + *(1 + mat)) << endl; } Live demo: http://cpp.sh/9drls
30th Jun 2019, 5:42 AM
To Seek Glory in Battle is Glorious
To Seek Glory in Battle is Glorious - avatar
+ 2
array index start from zero....u given index 1 so this wll print 5..
1st Jul 2019, 3:01 PM
Aurang Zeb
Aurang Zeb - avatar