Matrix and pointers

I dont understand why 4 is my answer?

1
2
3
4
  int m[][3]={1,2,3,4,5,6,7,8,9};
  int (*b)[3]=&m[0];
  int r=**(++b);
  std::cout << r;
The preincrement (++) operator on b does advance the pointer by 3 ints, due to the int [3] in the declaration of b.
After int (*b)[3]=&m[0];, b is pointing at the first row ({1,2,3})
after ++b, b is pointing at the second row ({4,5,6})
after the first *, the result of *(++b) is the second row itself (the array {4,5,6})
when the second * is applied, implicit conversion kicks in: a temporary pointer to the first element of {4,5,6} is constructed and then fed to operator*, which obtains that first element (the integer 4)

I'll try to make every step more explicit:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

int main()
{
  int m[3][3]={ {1,2,3},
                {4,5,6},
                {7,8,9} };

  int (*b)[3] = &m[0]; // b is pointing at the first row
// could also be written  int (*b)[3] = m; since the conversion is implicit

  int (*b2)[3] = ++b; // b2 is pointing at the second row

  int (&r2)[3] = *b; // r2 is the second row

  int* p3 = &r2[0]; // p3 is pointing at the first element of the 2nd row
// could also be written int* p3 = r2; since the conversion is implicit

  int r = *p3;
  std::cout << r;
}
Topic archived. No new replies allowed.