pointer to pointer

Hello forum,

I am going through a functional snippet of code that demonstrates the idea of pointer to pointer. Check the following snippet:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

class A{

    private:
       int ** mPtrArray;
       int mWidth, mHeight;
};

.................
..................

A::A(width,height): mWidth(width),mHeight(height)
{
   mPtrArray = new int*[mWidth];

   for(unsigned int i = 0; i < mWidth; ++i)
   {
       mPtrArray[i] = new int[mHeight];
   }
}


I am having trouble to understand the following :

 
mPtrArray = new int*[mWidth];


Some explanations ?

new int*[mWidth]; creates an array of int*.
So mPtrArray is a pointer to first element of array of pointers to int: pointer ... to pointers to intint**
What may (or may not) clarify is type alias:
1
2
3
4
5
6
7
8
9
using Column = int *;

Column * mPtrArray;

mPtrArray = new Column [mWidth];

for(unsigned int i = 0; i < mWidth; ++i ) {
  mPtrArray[i] = new int [mHeight];
}

The mPtrArray points to an array of "Columns".
Each column is an array of int.


PS. C/C++ uses "row-major" convention for matrices and thus has "array of rows", unlike the "column-major" semantics of your code.
See http://en.wikipedia.org/wiki/Row-major_order
Topic archived. No new replies allowed.