[C++] pointer to a 2D array of objects?

Soldato
Joined
23 May 2005
Posts
2,964
Location
Auckland, New Zealand
instead of this:

Tile * Grid = new Tile[GRIDWIDTH*GRIDHEIGHT];

I'd like a 2D array but this doesn't work:

Tile * Grid = new Tile[GRIDWIDTH][GRIDHEIGHT];

Anyone care to help? I know theres probably an easy solution to this.

Joe :)
 
in C and C++, a multi-dimensional array is merely an array of pointers to the next dimension :
Code:
Tile **Grid = new Tile *[GRIDWIDTH];
for (int i = 0; i < GRIDWIDTH; i++) {
        Grid[i] = new Tile[GRIDHEIGHT];
}
... and the reverse to deallocate it :)
 
or use STL vectors:

typedef std::vector<Tile> TileVec;
typedef std::vector<TileVec> GridType;

...

GridType Grid (GRIDWIDTH, TileVec (GRIDHEIGHT));

...initialise tiles...

std::cout << Grid[0][0];
 
Last edited:
Arrays have always been second class beasts in C, and this carries over with penalties to C++. The solution depends on what exactly you want to do with it.
 
or use STL vectors:

typedef std::vector<Tile> TileVec;
typedef std::vector<TileVec> GridType;

...

GridType Grid (GRIDWIDTH, TileVec (GRIDHEIGHT));

...initialise tiles...

std::cout << Grid[0][0];

How would I delete an array when declared like this? I know that its deleted when a program is closed but how would I delete it manually?
 
You could allocate Grid dynamically i.e.

GridType *Grid = new GridType (GRIDWIDTH, TileVec (GRIDHEIGHT));

...

delete Grid;

Unless Grid is very large, and you only need it for a short amount of time, there's not much point.
 
Back
Top Bottom