C++/Passing multidemensional array to function
Expert: Eddie - 8/22/2006
QuestionHi,
I need to pass at least one 2D array to a function. I'm using Dev-Cpp on Windows XP.
movePieces(pieceArray, i, movingNo);
this is how I'm currently calling the function - pieceArray is the array, while i and moving No are values needed by the function.
void movePieces(int *pieceArray, /*int &dim1, int &dim2,*/ int &i, int &moving);
this is the header file - the commented out part was from a book that suggests passing the dimensions of the array seperately - but that didn't work.
#include "movePieces.h"
void movePieces(int *rpieceArray, /*int &rdim1, int &rdim2,*/ int &ri, int &rmoving)
{
/*pieceArray = *rpieceArray[10][16];*/
int tempArray[8];
for(int j = 0; j < 7; j++)
{
tempArray[j] = pieceArray[j][rmoving];
pieceArray[j][rmoving] = pieceArray[j][ri];
pieceArray[j][ri] = tempArray[j];
}
}
I did see something online that said I could simply use "function(int *array)" and then use the commented out line in the body of the function - but again, no success
the compiler only complains that it "cannot convert `int (*)[16]' to `int*' for argument `1' to `void movePieces(int*, int&, int&)'"
Also, it may be necessary , later in the development process, for me to pass two arrays to a different function. Is this possible?
Any help you can give me with either question would be much appreciated.
Alicia
AnswerHello Alicia, thank you for the question.
Passing 2d arrays into functions is a nasty process, and I don't recommend doing it by pointer. In fact, I think you have to do it by reference, because I know that you have to specify the second number due to syntactical reasons. Try changing your function declaration to this:
void movePieces(int rpieceArray[][16] /*...*/)
Unless you are doing something syntactically wrong somewhere else, this should fix you up, ugly as it is.
Let me know if you need any more help.
- Eddie