动态分配3d数组

use*_*967 3 c++ dynamic multidimensional-array

关于动态分配3d数组我有点困惑.现在,我只是像这样分配一大块内存:

int height = 10;
int depth = 20;
int width = 5;

int* arr;
arr = new int[height * width * depth];
Run Code Online (Sandbox Code Playgroud)

现在我想更改3D数组中的值,例如:

//arr[depth][width][height]
arr[6][3][7] = 4;
Run Code Online (Sandbox Code Playgroud)

但是,我无法使用上面的代码来更改值.如何使用单个索引访问位置深度= 6,宽度= 3,高度= 7的元素?

arr[?] = 4;
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来动态分配3D数组?

yam*_*man 12

这样做的倾斜方式是:

int ***arr = new int**[X];
for (i = 0; i < z_size; ++i) {
  arr[i] = new int*[Y];
  for (j = 0; j < WIDTH; ++j)
    arr[i][j] = new int[Z];
}
Run Code Online (Sandbox Code Playgroud)


Jes*_*ood 7

索引到平坦的三维数组:

arr[x + width * (y + depth * z)]
Run Code Online (Sandbox Code Playgroud)

其中x,y和z分别对应于第一维,第二维和第三维,宽度和深度是阵列的宽度和深度.

这是一个简化x + y * WIDTH + z * WIDTH * DEPTH.


Aar*_*Cee 5

要拥有像 arr[height][width][depth] 之类的简单索引机制,并且要在分配的内存中将默认值初始化为 0,请尝试以下操作:

// Dynamically allocate a 3D array
/*  Note the parenthesis at end of new. These cause the allocated memory's
    value to be set to zero a la calloc (value-initialize). */
    arr = new int **[height]();
    for (i = 0; i < height; i++)
    {
        arr[i] = new int *[width]();
        for (j = 0; j < width; j++)
            arr[i][j] = new int [depth]();
    }
Run Code Online (Sandbox Code Playgroud)

这是相应的解除分配:

//Dynamically deallocate a 3D array

for (i = 0; i < rows; i++)
{
    for (j = 0; j < columns; j++)
        delete[] arr[i][j];
    delete[] arr[i];
}
delete[] arr;
Run Code Online (Sandbox Code Playgroud)


小智 5

3D 数组(在堆中)的分配和释放完全相反。在正确释放内存时要记住的关键一点是,使用关键字的次数与使用关键字的delete次数一样多。new这是我的 3D 数组初始化和清理代码:

int ***ptr3D=NULL;
ptr3D=new int**[5];

for(int i=0;i<5;i++)
{
    ptr3D[i] = new int*[5];  

    for(int j=0;j<5;j++)
    {
        ptr3D[i][j]=new int[5]; 

        for(int k=0;k<5;k++)
        {
            ptr3D[i][j][k]=i+j+k; 
        }
    }
}
//Initialization ends here
...
... //Allocation of values

cout << endl <<"Clean up starts here " << endl;

for(int i=0;i<5;i++)
{
    for(int j=0;j<5;j++)
    {
        delete[] ptr3D[i][j];   
    }
    delete[] ptr3D[i];
}
delete ptr3D;
Run Code Online (Sandbox Code Playgroud)

请注意,对于 3 个new关键字,delete已使用 3 个相应的关键字。这应该会清理堆中分配给 3D 数组的所有内存,并且可以使用 Valgrind 在每个阶段对其进行验证。