【问题标题】:The correct way to initialize a dynamic pointer to a multidimensional array? [duplicate]初始化指向多维数组的动态指针的正确方法? [复制]
【发布时间】:2013-08-18 20:43:15
【问题描述】:

当我将动态指针范围设置为 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];

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

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

【问题讨论】:

  • 别忘了删除它们
  • std::vector<std::unique_ptr<int>>

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


【解决方案1】:

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

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

  1. new int[4]; 调用 operator new function()
  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;
    

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

【讨论】:

    【解决方案2】:

    你想要这样的东西:

    int **P = new int*[7];
    p[0] = new int[5];
    p[1] = new int[5];
    ...
    

    【讨论】:

      【解决方案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];
      

      【讨论】:

        【解决方案4】:

        这会对一些调试编译器执行边界检查,使用动态大小并自动删除自身。唯一的问题是 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;
            }
        }
        

        【讨论】:

        • 不,它不执行边界检查。
        • 也可以按照以下方式进行初始化。 std::vector<:vector>> array2d(y_size, std::vector(x_size, 0));
        • 第二个 for 循环也有问题。应该有 x++ 而不是 y++
        猜你喜欢
        • 2016-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-11
        • 1970-01-01
        • 2015-04-28
        • 1970-01-01
        • 2015-12-31
        相关资源
        最近更新 更多