2012-04-20 200 views
3

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

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

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

现在,我想的三维阵列中更改值,说:

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

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

arr[?] = 4; 

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

+0

这是我认为的指针,如果你需要3个维度,那么不应该是int *** arr = new int [height] [width] [depth]; ? – 2012-04-20 00:34:30

回答

6

索引到扁平3维阵列:

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

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

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

+0

对不起,x对应于width元素,y是高度元素,z是深度元素,还是我有错?因此,要得到深度= 6,宽度= 3,高度= 7的元素:arr [3 + 5 *(7 + 20 * 6)] = arr [638]? – user974967 2012-04-20 01:50:46

+0

@ user974967:“x是高度”,“y是宽度”,“z是深度”。要访问'arr [6] [3] [7]'使用'arr [6 + 5 *(3 + 20 * 7)]''。基本上,高度,宽度,然后在这个顺序的深度。 – 2012-04-20 02:02:00

7

Ç这样做的倾斜的方法是:

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 [高度] [宽度] [深度],并且还具有在所分配的存储器的默认值被初始化为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; 
1

分配和解除分配用于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在每个阶段验证它。