# Need to pass a pointer of a unknown sized 2d array

• 01-02-2007
(Slith++)
Need to pass a pointer of a unknown sized 2d array

Basically Im making a Tetris game, I have a function 'getRandomPiece()' which I would like to return a random Tetris piece which is a 2d array. Problem is, not all pieces are the same dimensions (same width and height).

So after allot of reading it seems c++ cant return an array.

So then ill try passing a pointer to store the array. The problem with this is c++ wants me to declare the size of the array in the parameter which I dont know what its going to be yet.

Ideally in Java I can just go

Code:

```int[][] getRandomPiece(){       //Random logic     int[][] arr = {{1,1,0},                         {0,1,1}};       return arr; }```
Which is the best way to solve this problem?
• 01-02-2007
rynoon
I'd just use a vector of vectors and avoid this entire headache.
• 01-02-2007
DavidP
So this array represents the shape of the random piece, then?

I don't know how large scale this tetris game your making is, but a simple "piece" class would go a long ways to help out on such a problem. There are several ways you could approach this.

You could make a seperate class for each type of piece, and have them all derive from the base piece class. Then each piece would automatically store a 2d array with its shape inside. For example:

Code:

```class LSHAPE: public PIECE { private: int shape [][] = { {011}, {001}, {001} }; ...then comes the rest of the class... };```
You have to keep in mind that the pieces will be rotating, and therefore this matrix wont be staying the same.

Essentially the most states any piece could have is 4 different states, and so you could have 4 different matrixes, and then a variable that flags which matrix should be used for the display of pieces in your tetris game.

If you dont want to hold 4 different matrixes, I think some bitwise operations could be done to "rotate" the matrix.

Now, back to the problem at hand. If you created a seperate derived class for each piece, you could have you random logic that selects a piece, and then just return that piece (which already contains its correct matrix) instead of returning a matrix.

Example:

Code:

```PIECE *randomPiece ( ) { ...random piece logic... switch ( logic result ) { case LSHAPE_PIECE:     return new LSHAPE(); ...etc.... } }```
Does this help?
• 01-02-2007
(Slith++)
It does help, although in Java I have already written a algorithm to rotate a 2d array and would rather use that than pre-calculated rotations.

I guess each class such as LShape could have its own rotate function which only rotated its own shape...

Thanks for the ideas both of you.