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?
Below is the general form of declaring N-dimensional arrays: Syntax of a Multidimensional Array: data_type array_name[size1][size2]…. [sizeN];
dynamically allocated arrays To dynamically allocate space, use calls to malloc passing in the total number of bytes to allocate (always use the sizeof to get the size of a specific type). A single call to malloc allocates a contiguous chunk of heap space of the passed size.
Dynamic memory allocation allocates memory on the heap as needed at run time, instead of allocating memory statically on the stack. Dynamic memory allocation is beneficial when: You do not know the upper bound of an array. You do not want to allocate memory on the stack for large arrays.
C inclined way of doing this is:
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With