1

Basically I want to create a multidimensional array using a size variable passed to my class but am not sure how to do it.

I've tried doing

//Class header
Tile * gameTile;

//Class cpp
gameTile = new Tile[size][size];

It doesnt mind new Tile[size] but not [size][size]. Why is this?

taocp
  • 23,276
  • 10
  • 49
  • 62
Split
  • 259
  • 2
  • 5
  • 11
  • Expression must have a constant value. Ive changed the prototype and that to const but nothing :/ – Split Jun 02 '13 at 00:34
  • One of the dimension must be constant, read this http://stackoverflow.com/questions/936687/how-do-i-declare-a-2d-array-in-c-using-new – Djon Jun 02 '13 at 00:38

4 Answers4

4

That fails because only the first dimension of an allocated array may have a dynamic size. To overcome this limitation you can use a 2-dimensional vector:

std::vector<std::vector<Tile> > gameTile(size, std::vector<Tile>(size));
David G
  • 94,763
  • 41
  • 167
  • 253
  • How would I declare that in a class header? How would I change the size of it depending on the parameter passed to the init function? – Split Jun 02 '13 at 02:53
  • @Split Well vector has a [`resize()`](http://en.cppreference.com/w/cpp/container/vector/resize) member function, so you can use that. – David G Jun 02 '13 at 02:54
  • As for the class header - where are you intending to use this? Inside main, for a class? – David G Jun 02 '13 at 02:58
  • Am intending to use this in a class – Split Jun 02 '13 at 23:48
1

Like in the link of Vlad mentions, you could use vectors, or for something more quick you could use the following code to initialize the bidimentional array:

int i;
int ** intTile;
intTile = new  int*[5];

for (i = 0; i < 5; i++) {
    intTile[i] = new int[5];
}
  • It's not really any quicker to code than a vector of vectors and not really quicker to run than a specialized matrix class. It fails at memory management much more than both, though. – chris Jun 02 '13 at 00:43
0

you could do

Tile *gameTile = &((new Tile[size][size])[0][0]);

this store the address for the first element in your multy dimensional array to gameTile.

Anthony Raimondo
  • 1,621
  • 2
  • 24
  • 40
0

Although you want to use two dimensional arrays, I just want to point out for completeness that you can also use a one dimensional array for your purpose. If it is of dimension size by size you have:

gameTile = new Tile[size*size];
//now gameTile[y][x] becomes:
Tile t = gameTile[x + y*size];

//if array is not square
gameTile = new Tile[width*height];
//now gameTile[y][x] becomes:
Tile t = gameTile[x + y*width];