Skip to main content
gamedev.net
🔒 Locked

Allocating a 3D array

Started by MTclip 3 replies 300+ views
Original Post
MTclip
MTclip
never tried to allocate a 3d array.. just assummed it was like a 2d array Cell ***Cells; Cells = new **Cell[MAX_CELLS]; Cells = new *Cell[MAX_CELLS]; Cells = new Cell[MAX_CELLS]; that does not work... how is this done? thanks ;P
RDragon1
RDragon1
to allocate an array of pointers, its new T*[size]

with that said, why fall back on raw arrays like this, instead of using std::vector's or boost::multi_array ?
MaulingMonkey
MaulingMonkey
Quote:
Original post by RDragon1
or boost::multi_array ?


/sign

That said...

Cell *** Cells;Cells = new **Cell[ x_size ];for ( size_t x = 0 ; x < x_size ; ++x ) {    Cells[x] = new *Cell[ y_size ];    for ( size_t y = 0 ; y < y_size ; ++y ) {        Cells[x][y] = new Cell[ z_size ];    }}//access via Cells[X][Y][Z]


Alternatively, a single array may work better:

Cell * Cells = new Cell[ x_size * y_size * z_size ];//access via Cells[X + Y*x_size + Z*y_size*x_size]
RDragon1
RDragon1
If you're going to use raw arrays, consider organizing it like this, instead;

Cell*** cells = new Cell**[depth];for( std::size_t z = 0; z < depth; ++z ){  cells[z] = new Cell*[height];  for( std::size_t y = 0; y < height; ++y )  {    cells[z][y] = new Cell[width];  }}



or, IMO, better:
Cell* cells = new Cell[ width * height * depth ];//to access:cells[ (z * height*width) + (y * width) + x ];

Code-R
Code-R
That'll just make the syntaz ugly, an in the case of array[j][k], the compiler does that work for you, in a much better case sometimes.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.