Original Post
What are the syntaxes involved in declaring and accessing a dynamic 2D array (of integers for example)?
quote:Not in C++.
Original post by Cherez
A 2D array is really an array of arrays.
quote:This is illegal in C++ too. Try it. operator new can only allocate a single dimension.
Now you have to decide the size of the arrays. If you want them all the same size then simply:
array = new int[num_arrays][size_arrays];
int **array;
array = new int[arrayWidth];
for (int j = 0; j < arrayWidth; j++)
array[j] = new int[arrayHeight];
for (int j = 0; j < arrayWidth; j++)
delete [] array[j];
delete [] array;
#ifndef ARRAY2D_INCLUDED
#define ARRAY2D_INCLUDED
#include <algorithm>
template <typename T>
class cArray2D
{
T *m_pData;
T **m_pRows;
int m_iRows;
int m_iColumns;
//no copy && assign
cArray2D(const cArray2D&);
cArray2D& operator=(const cArray2D&);
public:
cArray2D(void):
m_pData(0), m_pRows(0), m_iRows(0), m_iColumns(0)
{}
cArray2D(int iRows, int iCols):
m_iRows(iRows), m_iColumns(iCols)
{
m_pData = new T[iRows * iCols];
m_pRows = new T*[iRows];
for(int i = 0; i < iRows; ++i)
m_pRows[i] = m_pData + i * iRows;
}
~cArray2D(void)
{
delete [] m_pData;
delete [] m_pRows;
}
T* operator[](int i){ return m_pRows[i];}
const T* operator[](int i) const { return m_pRows[i];}
int rows(void) const { return m_iRows;}
int columns(void) const { return m_iColumns;}
void swap(cArray2D& that)
{
std::swap(m_pData, that.m_pData);
std::swap(m_pRows, that.m_pRows);
std::swap(m_iRows, that.m_iRows);
std::swap(m_iColumns, that.m_iColumns);
}
void resize(int iRows, int iCols)
{
cArray2D arr( iRows, iCols);
iRows = std::min( iRows, rows());
iCols = std::min( iCols, columns());
while(iRows--)
for(int iX = 0; iX < iCols; ++iX)
arr[ iRows][ iX] = (*this)[ iRows][ iX];
swap( arr);
}
};
#endif
#define Index(x,y) (((x)-1)*dimx+(y)-1)
int * array2D=new int[dimx*dimy];
for (int x=0;x<dimx;x++)
for (int y=0;y<dimy;y++)
array2D[Index(x,y)]=0;
delete [] array2D;
This topic has been locked by a moderator. New replies are not allowed.
With your permission, GameDev.net uses analytics cookies to understand how people use the platform. You can accept analytics or continue with necessary cookies only. Learn more