Asked By
John C Reis
50 points
N/A
Posted on - 01/25/2015
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?
Dynamic Memory allocation of 3d array or more
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.
Â
Â
Dynamic Memory allocation of 3d array or more
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.