I am trying to return an array Data Member from one smaller 2D Array Object, and trying to insert the array into a larger 2D array object. But when attempting this, I came into two problems.
First problem is that I want to return the name of the 2D array, but I do not know how to properly syntax to return 2D Array name.
This is what my 2D Array data member looks like
private: int pieceArray[4][4]; // 2D Smaller Array
and I want to return this array into a function, but this one causes a compiler error:
int Piece::returnPiece() { return pieceArray; //not vaild // return the 2D array name }
I tired using this return type and it worked:
int Piece::returnPiece() { return pieceArray[4][4]; }
But I am unsure if this is what I want, as I want to return the array and all of it’s content.
The other problem is the InsertArray() function, where I would put the returnPiece() function in the InsertArray()’s argument.
The problem with the InsertArray() is the argument, heres the code for it:
void Grid::InsertArray( int arr[4][4] ) //Compiler accepts, but does not work { for(int i = 0; i < x_ROWS ; ++i) { for (int j = 0; j < y_COLUMNS ; ++j) { squares[i][j] = arr[i][j]; } } }
The problem with this is that it does not accept my returnPiece(), and if i remove the ‘[4][4]’, my compiler does not accept.
Mostly all these are syntax errors, but how do I solve these problems?
- Returning the whole pieceArray in returnPiece()
- The correct syntax for the argument in InsertArray()
- The argument of InsertArray() accepting the returnPiece()
These 3 are the major problems that I need help with, and had the same problem when I attempt to use the pointer pointer method. Does anyone know how to solve these 3 problems?
When passing your array around, you have to decide whether or not you want to make a copy of the array, or if you just want to return a pointer to the array. For returning arrays, you can’t (easily) return a copy – you can only return a pointer (or reference in C++). For example:
To use it, call it like so:
Note the similarity between the type declaration and using it – the parentheses, dereferencing operator
*, and brackets are in the same places.Your declaration for
Grid::InsertArrayis correct – it takes one argument, which is a 4×4 array of integers. This is call-by-value: whenever you call it, you make a copy of your 4×4 array, so any modification you make are not reflected in the array passed in. If you instead wanted to use call-by-reference, you could pass a pointer to an array instead:These type declarations with pointers to multidimensional arrays can get really confusing fast. I recommend making a
typedeffor it like so:Then you can declare your functions much more readable:
You can also use the cdecl program to help decipher complicated C/C++ types.