NEW with multidim arrays???

Started by
1 comment, last by Jedyte 22 years, 7 months ago
I'm kinda new on dynamic memory allocation (no pun intended ^_^), and I don't know how do this: I have a 3 layered map-structure of variable width and height in a class, and I want to allocate memory to it. Is this the way to do it, cause I don't know how to use new with multidimensional arrays.

class Map
{
   Map(int width, int height);
   // ...
   Tile _content[3][][];
};


Map::Map(int width, int height)
{
   for(int layer = 0; layer < 3; ++layer)
      _content[layer] = new Tile[width][height];
}
 
Edited by - Jedyte on September 11, 2001 3:56:53 PM
And the price we paid was the price men have always paid for achieving paradise in this life -- we went soft, we lost our edge. - "Muad'Dib: Conversations" by the Princess Irulan
Advertisement
quote:
I'm kinda new on dynamic memory allocation

heheh2hhaha4hha, heh, hoh, weeeee

    template<typename T>class CArray3D{public:	CArray3D(int x, int y, int z) : m_cRows(x), m_cCols(y), m_cDepth(z), m_Array(0)	{	m_Array = new (T**)[m_cRows];	_ASSERT(m_Array);	for(int i=0; i<m_cRows; i++)		{		m_Array[i] = new (T*)[m_cCols];		for(int j=0; j<m_cCols; j++)			m_Array[i][j] = new T[m_cDepth];		}	}virtual ~CArray3D()	{	for(int i=0; i<m_cRows; i++)		{		for(int j=0; j<m_cCols; j++)			delete[] m_Array[i][j];		delete[] m_Array[i];		}	delete[] m_Array;	}T** operator[](int i)	{	_ASSERT( (i>=0) && (i<m_cRows) );	return m_Array[i];	}T& operator()(int i, int j, int k)	{	_ASSERT( (i>=0) && (i<m_cRows) );	_ASSERT( (j>=0) && (j<m_cCols) );	_ASSERT( (k>=0) && (k<m_cDepth) );	return m_Array[i][j][k];	}protected:	T*** m_Array;	const int m_cRows;	const int m_cCols;	const int m_cDepth;private:	//You can (should) make this public if you implement it	CArray3D(const CArray3D&);};    


Magmai Kai Holmlor
- Not For Rent

Missed the 3D part first time arround...

Edited by - Magmai Kai Holmlor on September 11, 2001 10:05:01 PM
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
Tanx!
So it as I feared, you have to iterate through te structure.
Wasn''t sure you could allocate mem in an already dynamically allocated structure..
And the price we paid was the price men have always paid for achieving paradise in this life -- we went soft, we lost our edge. - "Muad'Dib: Conversations" by the Princess Irulan

This topic is closed to new replies.

Advertisement