0

I have the following code in C++:

#include <iostream>
using namespace std;
int main()
{
    int a[2][4] = {3, 6, 9, 12 , 15, 18, 21, 24};
    cout << *(a[1]+2) << *(*(a+1)+2) << 2[1[a]];
    return 0;
}

Now when I run the code, it outputs a[1][2] which is 21 three times, meaning that the three expressions in the cout statement all refer to a[1][2], but I don't understand how the three expressions work although I know basically what an address and a pointer is, the third expression seems clearer than the first two, it is similar to a[1][2] in shape but looks like it's flipped inside out. Can someone explain how these expressions work? and if there's a reference or a list of the ways of indexing an array please mention it also.

ammar
  • 47
  • 4
  • 1
    `X[Y]` is exactly the same as `*(X+Y)` which is the same as `*(Y+X)` that's all you need to know – john Aug 09 '22 at 11:01
  • the dupe explains the 1d case. I suggest you to first understand the 1d case before you turn to 2d – 463035818_is_not_an_ai Aug 09 '22 at 11:01
  • 2
    But `2[1[a]]` is really a kind of a joke. If you turned in that code on a real job, you'd be fired. – john Aug 09 '22 at 11:03
  • fwiw, what you are observing is quirks of c-style arrays. They have more quirks, some of them are much worse, and almost all of them are avoided by using `std::array` – 463035818_is_not_an_ai Aug 09 '22 at 11:05
  • There is actually a lot of going on here: 1) Aggregate initialisation brackets elision makes array of arrays `{{3, 6, 9, 12}, {15, 18, 21, 24}}` out of `{3, 6, 9, 12 , 15, 18, 21, 24}`; 2) `a[1]` and `*(a+1)` both refer to the second array `{15, 18, 21, 24}`; 3) second array + 2 means third element of the array `21` in the first and second sample; 4) `1[a]` is evaluated into `*(1 + a)` and `2[1[a]]` is `*(2+*(1+a))`, which is again third element 21 – The Dreams Wind Aug 09 '22 at 11:07
  • What this means is that I wouldn't hire any engineer brave (or stupid) enough to write code like this. There is so many indirections and dependency on operator precedences, that the code is almost intractible. I would not even try to start to understand but ask for a rewrite. – Pepijn Kramer Aug 09 '22 at 11:16

0 Answers0