dynamically allocating 3d array

c++, dynamic, multidimensional-array

Solution

To index into the flat 3-dimensional array:

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

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

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

Problem

I'm a little confused about dynamically allocating a 3d array. Right now, I'm just allocating one big block of memory like so: ``` int height = 10; int depth = 20; int width = 5; int* arr; arr = new int[height * width * depth]; ``` Now I'd like to change a value in the 3D array, say: ``` //arr[depth][width][height] arr[6][3][7] = 4; ``` However, I can't use the above code to change the value. How can I use a single index to access the element at position depth = 6, width = 3, height = 7? ``` arr[?] = 4; ``` Is there a better way to dynamically allocate a 3D array?

Original source