1

Let's say I have this to create a multidimensional array dynamically:

int* *grid = new int*[gridSizeX];

for (int i=0; i<gridSizeX; i++) {
  grid[i] = new int[gridSizeY];
}

Shouldn't be possible now to access elements like grid[x][y] = 20?

dmessf
  • 1,025
  • 3
  • 11
  • 19
  • 2
    Yes. {Assuming `x` is within [0, `gridSizeX`) and `y` is within [0, `gridSizeY`).} I recommend you use `std::vector` to manage memory for you. – GManNickG May 06 '10 at 01:31
  • lets see here, in the related links we find http://stackoverflow.com/questions/1024772/dynamic-multidimensional-array and http://stackoverflow.com/questions/799373/array-of-pointers-to-multidimensional-arrays and http://stackoverflow.com/questions/1584100/converting-multidimensional-arrays-to-pointers-in-c and there are others: I've answered at least three versions of this many moons ago. – dmckee --- ex-moderator kitten May 06 '10 at 01:45
  • AraK answered something similar extensively here: http://stackoverflow.com/questions/1946830/multidimensional-variable-size-array-in-c – Georg Fritzsche May 06 '10 at 02:13

2 Answers2

3

Yes, this should work fine.

But... you might want to consider using standard containers instead of manually managing memory:

typedef std::vector<int> IntVec;
typedef std::vector<IntVec> IntGrid;
IntGrid grid(gridSizeX, IntVec(gridSizeY));

grid[0][0] = 20;
Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236
0

Yes - but in C/C++ it will be laid out as grid[y][x].

nevelis
  • 736
  • 6
  • 17
  • Pardon me - I mean it will be laid out in memory as grid[y][x]. And agree with gf - in C++ you may want to use standard containers, as then you can check their .size() and avoid any slipups :) – nevelis May 06 '10 at 01:35