Double pointer array in c++

前端 未结 3 1325
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  梦毁少年i
    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;
    

提交回复
热议问题