0

I've been working off of Passing a 2D array to a C++ function , as well as a few other similar articles. However, I'm running into a problem wherein the array I'm creating has two dimensions of variable size.

The initialization looks like:

int** mulePosition;
mulePosition = new int *[boardSize][boardSize][2];

The function looks like:

int moveMule (int boardSize, int ***mulePosition)

And the references look like

moveMule (boardSize, mulePosition)

Boardsize is defined at the beginning of the function, but may change per execution. The array, properly sized, would be int [boardSize][boardSize][2].

Community
  • 1
  • 1
jbzdarkid
  • 134
  • 11
  • 1
    Use some sensible C++ type, like a vector of vectors. – David Schwartz Mar 03 '14 at 22:25
  • This initialization is [ill-formed, the types are incompatible](http://coliru.stacked-crooked.com/a/c78ff1c11be7dfd1). – dyp Mar 03 '14 at 22:28
  • Yes, the code does not work. The declaration is int** yet the array is 3-dimensional. However, int*** throws its own errors. – jbzdarkid Mar 03 '14 at 22:33
  • @jbzdarkid That's because `int*[n][n][2]` is a *array of n arrays of n arrays of 2 pointer-to-`int`*. And that's the reason why you typically *don't* want to use these kind of composed types when you have alternatives such as classes wrapping flat data structures or typedefs. – dyp Mar 03 '14 at 22:52

2 Answers2

0

Either use a plain '3-dimensional' array via

int* mulePosition = new int[boardsize*boardsize*2];

and address its elements calculating the offset from the beginning: mulePosition[a][b][c] is mulePosition[boardSize*2*a + 2*b + c],

or use array of arrays of arrays (which would correspond to your int*** declaration) or better (and simpler) vector of vectors of vectors, although the initialization would be a little more complex (you would need to initialize every array/vector).

nullptr
  • 10,678
  • 1
  • 17
  • 16
0

Either use a std::vector<std::vector<int>> if boardSize is not a const or std::array<std::array<boardSize>, boardSize> (see Multidimensional std::array for how to initialize the std::array).

That being said, it looks like a good idea to hide this in a class Board which provides a nice interface.

Jens
  • 8,115
  • 1
  • 21
  • 37