本文介绍了C ++中的双指针数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关BTree的程序,在那里遇到了: BTreeNode ** C .我知道这是一个2D数组,但它初始化为 C = new BTreeNode * [2 * t]; .我不明白:这是具有动态行和2t列的2d数组吗?谢谢.

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.

推荐答案

您可能很了解 double * 是指向 double 元素的指针.同样, double ** 是指向 double * 元素的指针,该元素本身就是一个指针.同样, double *** 是指向 double ** 元素的指针,依此类推.

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.

当将数组实例化为 T 类型时,通常会执行 new T [size]; .例如,对于 double 的数组,您编写 new double [size]; .如果您的类型 T 本身就是一个指针,则完全相同:您编写 new double * [size]; ,然后得到一个指针数组.

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.

在您的情况下, BTreeNode * 是指向 BTreeNode 的指针,而 BTreeNode ** 是指向 BTreeNode **的指针/code>,它是指向 BTreeNode 的指针.通过执行 new BTreeNode * [size]; 实例化它时,您将获得一个指向 BTreeNode 元素的指针数组.

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.

但是实际上,在此步骤中您没有2D数组,因为没有分配新分配的数组中的指针.通常的方法是以下示例:

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;

这篇关于C ++中的双指针数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 01:29