c++ - 初始化指向多维数组的动态指针的正确方法?

标签 c++ pointers dynamic c++11 multidimensional-array

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

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];

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

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

最佳答案

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

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

  1. new int[4]; 调用 operator new function()
  2. 为 4 个整数分配内存。
  3. 返回对此内存的引用。
  4. 要绑定(bind)这个引用,你需要有与返回引用相同类型的指针,所以你这样做

    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
}

这是它的样子:

enter image description here

释放内存

  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;
    

避免内存泄漏和悬空指针!

关于c++ - 初始化指向多维数组的动态指针的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18273370/

相关文章:

c++ - 模板成员函数无法自动推断类型

c++ - unique_ptr 参数类型的模板参数推导指南?

c++ - 管理指向派生对象的指针集合的最佳方法

c - 将链表分成两半

JQuery使用Prepend动态设置ID

c++ - 为什么赋值运算符一开始就返回任何东西?

c++ - 带有指针 vector 的 glbufferdata C++

c - 代码结果说明

c# - 是否可以使用 ExpandoObject 创建运行时属性?

c - 用函数初始化c中动态分配的二维数组