Constructors for creating 2d arrays

• 06-29-2005
Welshy
Constructors for creating 2d arrays
Hey guys, been a while since ive posted on here.......had a break to take some exams, ANYWAY lets get straight to my problem :)

I'm making a small minesweeper game, and i want the player to be able to select the size of the minefield, but the constructor is turning out to be a bit of a problem. The best i could come up with it below, but ill need to define i and j as ints, but i'd rather not create another two variables, is there a better way? thanks

Code:

int m_Height;
int m_Width;
Field(char field[int i][int j]);          // constructor
char m_MineField[][];                      // minefield itself

Code:

Field(char field[i][j]): m_MineField[m_Width][m_Height](field[i][j])
• 06-29-2005
Code:

int m_Height;
int m_Width;
char **m_MineField;
m_MineField = new char*[m_Height];
for(int i = 0; i < m+Height; ++i)
m_MineField = new char[m_Width];

look up declaring and using multidimensional arrays using dynamic memory for further details.
• 06-29-2005
Daved
Use a two dimensional vector instead. It is easy to size to whatever size the user specifies.
• 06-29-2005
Welshy
Oh didnt know you could use a 2d vector, thanks for that Daved.

Before anyone calls me stupid, im learning incase you couldnt guess :P
• 06-29-2005
hk_mp5kpdw
You can also use a templated grid structure/class:

Code:

template<int height=5,int width=5>
struct grid
{
int data[height][width];
grid()
{
// Initialize the grid
}
int GetWidth() const
{
return width;
}
int GetHeight() const
{
return height;
}
// Other member functions...
};

...

grid<> minefield1;      // Creates a default 5x5 minefield
grid<10,20> minefield2;  // Creates a 10x20 minefield

• 06-29-2005
Welshy
whoa i havent got onto templates yet, one step at a time, lol, cheers anyway