Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically allocating 3d array

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?

like image 498
user974967 Avatar asked Apr 20 '12 00:04

user974967


People also ask

How do you declare a 3d array dynamically?

Below is the general form of declaring N-dimensional arrays: Syntax of a Multidimensional Array: data_type array_name[size1][size2]…. [sizeN];

How do you dynamically allocate an array?

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.

Can we use dynamic memory allocation in array?

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.


1 Answers

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];
}
like image 114
yaman Avatar answered Sep 30 '22 19:09

yaman