Array of pointers to pointers

Hi forum,

How to declare an array of pointers to pointers ?

 
Cell mCell = new Cell* [width];


Is that how it is to be defined? I did it without much of an understanding.

Some explanation would be helpful.


Thanks
1
2
3
4
5
6
7
8
9
10
const int width = 10;

// Array of Cell objects.
Cell mCell[width];

// Array of pointers to Cell objects.
Cell* mCell[width];

// Array of pointers to pointers to Cell objects.
Cell** mCell[width];
What does the following mean then ? I got it in a book without much of an explanation

 
Cell mCell = new Cell* [width];
It doesn't compile. You will have to change it slightly.

 
Cell* mCell = new Cell [width];
This creates an array of Cell objects. The mCell pointer will point to the first Cell object in the array.

 
Cell** mCell = new Cell* [width];
This creates an array of pointers to Cell objects. The mCell pointer will point to the first pointer in the array.
Does the following compile at your end ?

1
2
3
4
5
6
7
8
Spreadsheet::Spreadsheet(int inWidth, int inHeight) :
  mWidth(inWidth), mHeight(inHeight)
{
  mCells = new SpreadsheetCell* [mWidth];
  for (int i = 0; i < mWidth; i++) {
    mCells[i] = new SpreadsheetCell[mHeight];
  }
}


here mCell is of type SpreadsheetCell **

It compiles at my end , but the following line is not clear enough for me :

 
  mCells = new SpreadsheetCell* [mWidth];
I can't compile incomplete code but it looks fine.

Is it the extra * that confuse you? Is this clear to you (T could be any type)?
 
T* foo = new T[10];

So T is the type of the elements in the array. If you want store pointers to objects of some other type U in the array you just replace T by U*.
 
U** foo = new U*[10];
Topic archived. No new replies allowed.