27

当我将动态指针范围设置为二维或更高时,我一直运气不佳。例如,我想要一个指向二维数组的指针。我知道:

int A[3][4];
int (*P)[4] = A;

完全合法(即使我不完全理解为什么)。考虑到:

int *P = new int[4];

工作,我想象:

int **P = new int[5][7];

也可以,但不是。此代码说明了错误:

Error: A value of type "(*)[7]" cannot be used to initialize an entity of
       type "int **"

通过看到这一点,新部分变成了一个指向我制作的 7 个整数数组的指针:

int (*P)[4] = new int[7][4];

这确实有效,但这不是我想要完成的。通过这样做,我仅限于至少对任何后续维度使用常量值,但我希望它在运行时完全定义,因此是“动态的”。

我怎样才能让这个多维指针工作?

4

4 回答 4

71

让我们从一些基本的例子开始。

当你说int *P = new int[4];

  1. new int[4];调用操作员新函数()
  2. 为 4 个整数分配内存。
  3. 返回对此内存的引用。
  4. 要绑定此引用,您需要具有与返回引用相同类型的指针,因此您可以这样做

    int *P = new int[4]; // As you created an array of integer
                         // you should assign it to a pointer-to-integer
    

对于多维数组,您需要分配一个指针数组,然后用指向数组的指针填充该数组,如下所示:

int **p;
p = new int*[5]; // dynamic `array (size 5) of pointers to int`

for (int i = 0; i < 5; ++i) {
  p[i] = new int[10];
  // each i-th pointer is now pointing to dynamic array (size 10)
  // of actual int values
}

这是它的样子:

在此处输入图像描述

释放内存

  1. 对于一维数组,

     // need to use the delete[] operator because we used the new[] operator
    delete[] p; //free memory pointed by p;`
    
  2. 对于二维数组,

    // need to use the delete[] operator because we used the new[] operator
    for(int i = 0; i < 5; ++i){
        delete[] p[i];//deletes an inner array of integer;
    }
    
    delete[] p; //delete pointer holding array of pointers;
    

避免内存泄漏和悬空指针

于 2013-08-16T12:39:53.353 回答
7

你想要这样的东西:

int **P = new int*[7];
p[0] = new int[5];
p[1] = new int[5];
...
于 2013-08-16T12:42:08.790 回答
3

另一种方法是将一维数组用作二维数组。这样,您只需分配一次内存(一个连续块);

int *array;
size_t row=5,col=5;
array = (int*)malloc(row*col*sizeof(int)) //or new int[row*col]

这将导致与“int array[5][5]”相同。

访问您刚刚执行的字段:

array[1 //the row you want
 * col //the number of columns
+2//the column you want
] = 4;

这等于:

array[1][2];
于 2013-08-16T13:19:24.793 回答
2

这会对一些调试编译器执行边界检查,使用动态大小并自动删除自身。唯一的问题是 x 和 y 正好相反。

std::vector<std::vector<int>> array2d(y_size, std::vector<int>(x_size));

for (int y = 0; y < y_size; y++)
{
    for (int x = 0; x < x_size; y++)
    {
        array2d[y][x] = 0;
    }
}
于 2013-08-16T22:12:11.343 回答