Dynamic allocation of a 3d array

I am a bit confused about the dynamic allocation of a 3d array. Right now, I'm just allocating one large block of memory as follows:

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

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

Now I would like to change the value in a 3D array, say:

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

However, I cannot use the above code to change the value. How can I use one index to access an element at a depth of position = 6, width = 3, height = 7?

arr[?] = 4;

Is there a better way to dynamically allocate a 3D array?

+3
source share
4 answers

To index into a flat three-dimensional array:

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

Where x, y and z correspond to the first, second and third sizes, respectively, and the width and depth are the width and depth of the array.

This is a simplification x + y * WIDTH + z * WIDTH * DEPTH.

+6

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

, 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;
+3

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;

Note that new3 matching deletekeywords were used for 3 keywords. This should clear all the memory allocated to the 3D array on the heap, and Valgrind can be used to check at each stage.

+1
source

All Articles