Double pointer array in c++

You probably well know that double* is a pointer to a double element. In the same way, double** is a pointer to a double* element, which is itself a pointer. Again, double*** is a pointer to a double** element, and so on.

When you instanciate an array to a type T, you usually do new T [size];. For example, for an array of double, you write new double[size];. If your type T is a pointer itself, it’s exactly the same : you write new double*[size];, and you get an array of pointers.

In your case, BTreeNode* is a pointer to BTreeNode, and BTreeNode** is a pointer to BTreeNode* which is a pointer to BTreeNode. When you instanciate it by doing new BTreeNode*[size]; you get an array of pointers to BTreeNode elements.

But actually, at this step you don’t have a 2D array, because the pointers in your freshly allocated array are NOT allocated. The usual way to do that is the following example :

int num_rows = 10;
int num_cols = 20;
BTreeNode** C = new BTreeNode*[num_rows];
for(int i = 0; i < num_rows; i++)
{
  // Then, the type of C[i] is BTreeNode*
  // It's a pointer to an element of type BTreeNode
  // This pointer not allocated yet, you have now to allocate it
  C[i] = new BTreeNode [num_cols];
}

Don’t forget to delete your memory after usage. The usual way to do it is the following :

for(int i = 0; i < num_rows; i++)
  delete [] C[i];
delete [] C;

Leave a Comment