Question

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].

No correct solution

OTHER TIPS

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).

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top