Double pointer array in c++

前端 未结 3 1324
没有蜡笔的小新
没有蜡笔的小新 2021-01-29 11:11

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 *[

相关标签:
3条回答
  • 2021-01-29 11:14

    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.

    0 讨论(0)
  • 2021-01-29 11:16

    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;
    
    0 讨论(0)
  • 2021-01-29 11:25

    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.

    0 讨论(0)
提交回复
热议问题