three-dimensional dynamically allocated array

Started by
7 comments, last by CProgrammer 20 years, 1 month ago
I''ve never seen a 3d-array that is dynamically allocated. As int ***ar; and then offcourse allocate. Is this allowed. If so is it considered bad practive or is there no reason not to use it. -CProgrammer
Advertisement
That''s not 3D, that''s just a pointer to a pointer to a pointer.
A 3D array is a matrix with dimensions [D1][D2][D3].
Like unsigned char* MyMat=new unsigned char[D1*D2*D3];
This is useful in for example 3D pathfinding, where using a matrix together with progressive pathfinding can save quite a bit of memory compared to the standard linked list.
Cant I also do this:

int ***a;a = new int**[size_1];for(i = 0; i < size_1; i++){a = new int*[size_2];<br>for(i2 = 0; i2 < size_2; i2++)<br>{<br>a[i2] = new int[size_3];<br>}<br>}<br>  </pre>  <br><br>EDIT: Hmm the index makes my text italic<br><br>-CProgrammer        <br><br><SPAN CLASS=editedby>[edited by - CProgrammer on March 18, 2004 7:52:34 AM]</SPAN>   <br><br><SPAN CLASS=editedby>[edited by - CProgrammer on March 18, 2004 7:53:30 AM]</SPAN>
it''s still not a 3d array. it''s an array of arrays of arrays of ints.



If that''s not the help you''re after then you''re going to have to explain the problem better than what you have. - joanusdmentia

davepermen.net
If that's not the help you're after then you're going to have to explain the problem better than what you have. - joanusdmentia

My Page davepermen.net | My Music on Bandcamp and on Soundcloud

Ok I see the point.
However would it suffice as an array of two-dimensional arrays.
And if so, is it good practice or should I create some struct and then make an array of that.
-CProgrammer

int *a;

int size=32;

int size2=size*size;

// allocate 3d array
a= new int [ size*size*size ];

// to access simply use

int val = a[ i+j*size+k*size2 ];

if size are byte aligned you can substitute the multiplication
with power of 2 shifts, note that the compiler internally if
optimized try to do a similar thing
read up on boost.multi_array
Could use a vector of vectors of vectors too, pretty ugly though.

#include<vector>unsigned int x = 10, y = 20, z = 20;std::vector<std::vector<std::vector<int> > > threed(x, std::vector<std::vector<int> >(y, std::vector<int>(z)));
A vector of vectors has it''s uses, but it''s not a fast way for an n-dimensional matrix. Instead, just allocate a linear segment of memory and address it as an n-matrix.

This topic is closed to new replies.

Advertisement