I am trying to create a tic-tac-toe game for a homework project, but I am stuck in not knowing how to pass an array. Currently, I have this:
Prototype:
void displayBoard(char);
Variables:
const int COLS = 3;
const int ROWS = 3;
char board[ROWS][COLS] = {'*', '*', '*', '*', '*', '*', '*', '*', '*'};
Function call:
displayBoard(board);
Function:
void displayBoard(char board)
{
//DISPLAYBOARD displayBoard shows the current tic-tac-toe board
//along with proper spacing
cout << "---------------------" << endl << endl;
cout << " | | " << endl;
cout << " " << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << endl;
cout << "_____|_____|_____" << endl;
cout << " | | " << endl;
cout << " " << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << endl;
cout << "_____|_____|_____" << endl;
cout << " | | " << endl;
cout << " " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << endl;
cout << " | | " << endl;
}
I have tried several variations of passing the multidimensional array to the function displayBoard but I constantly get errors such as this one:
'void displayBoard(char)' cannot convert argument 1 from 'char[3][3]' to 'char' and if I leave the parenthesis () blank I also get an error saying 'board is not initialized' which it isn't, and I don't want to use a global variable.
Prototype should be the unintuitive:
void displayBoard(const char (&board)[ROWS][COLS]);
Using std::array<std::array<char, 3u>, 3u>
would have more intuitive syntax.
You can use templates for the displayBoard method if you need to display boards of differents size:
template <int SizeX, int SizeY>
void displayBoard(const char (&board)[SizeX][SizeY])
{
cout << "---------------------" << endl << endl;
cout << " | | " << endl;
cout << " " << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << endl;
cout << "_____|_____|_____" << endl;
cout << " | | " << endl;
cout << " " << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << endl;
cout << "_____|_____|_____" << endl;
cout << " | | " << endl;
cout << " " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << endl;
cout << " | | " << endl;
}
But be careful and always check you're accessing existing indexes in your array
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.