Dynamic Memory allocation of 3d array or more

Asked By 50 points N/A Posted on -
qa-featured

I am learning c++ and I have been coding in it for 3 months now. I am comfortable with array, 2 dimensional array and dynamic allocation of memory. So I can use pointers comfortably. But yesterday I tried to dynamically allocate an array with more than two dimensions and I could not do it. I followed the simple steps which are used in 2 dimensional array but it didn't work. How can we use pointers to dynamically allocate a 3 dimensional array or more?

SHARE
Answered By 0 points N/A #180876

Dynamic Memory allocation of 3d array or more

qa-featured

Hi John,

In order to allocate a 3-dimensional array, memory has to be allocated for the data, then memory for an array of pointers to data rows and finally, memory is to be allocated for an array of pointers to their subsets.
 
For indexing into a 3-d array,
 
arr[x + width * (y + depth * z)]
 
Where x, y and z refer to the first, second and third dimensions respectively and width and depth are the width and depth of the array.
 
Regards,
Anyet

 

Answered By 0 points N/A #180877

Dynamic Memory allocation of 3d array or more

qa-featured

Well there are two ways to solve your problem. One is you can allocate 1D array of pointers to a 1D array, it made array of arrays. Second one is much difficult and it have some other consequences too but it is more appropriate way to allocate 3D array as contiguous chunk. If you know about contiguous chunk then it is well and good, just give it a try your problem will be solved.

Related Questions