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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18273370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:50:27  来源:igfitidea点击:

The correct way to initialize a dynamic pointer to a multidimensional array?

c++pointersdynamicc++11multidimensional-array

提问by Jader J Rivera

I've been having bad luck with with dynamic pointers when I range them to 2 dimensions and higher. For example I want a pointer to a 2D array. I know that:

当我将动态指针范围扩展到 2 维和更高维度时,我对动态指针一直很不走运。例如,我想要一个指向二维数组的指针。我知道:

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

Is completely legit (even if I don't completely understand why). Taking into consideration that:

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

int *P = new int[4];

works, I imagined that:

工作,我想象:

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

Would also work, but it's not. This code states the error:

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

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

By seeing this the new part becomes a pointer to an array of 7 integers I made:

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

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

And this does work but it's not what I want to accomplish. By doing it like that I'm limited to at least using a constant value for any subsequent dimension, but I want it to be fully defined at run time and therefore "dynamic".

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

How could I go and make this multidimensional pointer work??

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

回答by Dipak Ingole

Let's start with some basic examples.

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

When you say int *P = new int[4];

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

  1. new int[4];calls operator new function()
  2. allocates a memory for 4 integers.
  3. returns a reference to this memory.
  4. to bind this reference, you need to have same type of pointer as that of return reference so you do

    int *P = new int[4]; // As you created an array of integer
                         // you should assign it to a pointer-to-integer
    
  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
    

For a multi-idimensional array, you need to allocate an array of pointers, then fill that array with pointers to arrays, like this:

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

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
}

Here is what it looks like:

这是它的样子:

enter image description here

在此处输入图片说明

To free the memory

释放内存

  1. For one dimensional array,

     // need to use the delete[] operator because we used the new[] operator
    delete[] p; //free memory pointed by p;`
    
  2. For 2d Array,

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

Avoid memory leakage and dangling pointers!

避免内存泄漏和悬空指针

回答by Paul Evans

You want something like:

你想要这样的东西:

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

回答by the baconing

Another approach would be to use a 1D array as an 2D array. This way you only have to allocate the memory once (one continous block);

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

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

This would result in the same as "int array[5][5]".

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

to access the fields you just do:

访问您刚刚执行的字段:

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

This is equal to:

这等于:

array[1][2];

回答by Neil Kirk

This performs bounds checking on some debug compilers, uses dynamic size and deletes itself automatically. The only gotcha is x and y are the opposite way round.

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