繁体   English   中英

动态分配3d数组

[英]dynamically allocating 3d array

我对动态分配3d数组有些困惑。 现在,我只是像这样分配一个大的内存块:

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

int* arr;
arr = new int[height * width * depth];

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

//arr[depth][width][height]
arr[6][3][7] = 4;

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

arr[?] = 4;

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

C的倾斜方式是:

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

索引到平面3维数组中:

arr[x + width * (y + depth * z)]

其中x,y和z分别对应于第一,第二和第三维,而width和depth是数组的宽度和深度。

这是x + y * WIDTH + z * WIDTH * DEPTH的简化。

要具有简单的索引机制(如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]();
    }

这是对应的释放:

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

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;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM