Double pointer array in c++

ぐ巨炮叔叔 提交于 2021-01-20 13:41:09

问题


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 *[2*t];. I can't understand this: is this a 2d array with dynamic rows and 2t columns ? Thanks.


回答1:


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;



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/36764695/double-pointer-array-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!