I was reading a program about BTree, there I came across this : BTreeNode **C
. I understand that it is a 2d array but it was initialized as C=new BTreeNode *[
The statement C=new BTreeNode *[2*t];
allocates space for 2*t
instances of type BTreeNode *
and therefore returns a type BTreeNode **
pointing to the first element of such instances. This is the first dimension of your array, however no memory has been allocated for the second dimension.
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;
Yes. If the array is being indexed column-major order (so C[3][4] is the 5th element of the 4th column) then C could, potentially, have ragged (differently sized) columns.
Look for some code that allocates memory for each column, i.e.
C[i] = new BTreeNode[length];
in a loop over i, that would indicate that the 2D array has the same length per column.