pointers and multi dimensional arrays

Jan 22, 2017 at 2:07pm
Hi guys I'm trying to grasp the concept of how pointers work with multi dimensional arrays but I'm finding it hard,

I know this code will get the value of whats in the single dimensional array by dereferencing it

1
2
  int a[2];
  cout << *(a+2);


this will print out the last result in the array a which is a garbage value BUT

1
2
3

  int b[2][2];
  cout << *(b+2);


how come when I use the dereference operator on this expression it actually prints out a memory address not the actual value of b+2

thanks
Jan 22, 2017 at 3:03pm
how come when I use the dereference operator on this expression it actually prints out a memory address not the actual value of b+2


since b is a 2 * 2 matrix its 2 rows are at b[0] and b[1], so b+2 is not a valid memory address. In general for pointer representations of 2D arrays think about the memory allocation first in terms of the rows and then for each row in terms of it's columns, something along the line of the following program:
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 b[2][2] {{1,2},{3,4}};

    int* firstRow = b[0];
    int* secondRow = b[1];

    int* firstRowfirstCol = firstRow;
    int* firstRowsecondCol = firstRow + 1;

    int* secondRowfirstCol = secondRow;
    int* secondRowsecondCol = secondRow + 1;


    std::cout << "Element (0,0): " << *firstRowfirstCol << '\n';
    std::cout << "Element (0,1): " << * firstRowsecondCol << '\n';
    std::cout << "Element (1,0): " << *secondRowfirstCol << '\n';
    std::cout << "Element (1,1): " << *secondRowsecondCol << '\n';
}

Jan 22, 2017 at 4:06pm
thanks gunnerfunner =)
Topic archived. No new replies allowed.