Hello! I'm writing a simple tic-tac-toe game as a school assignment. Everything worked great, but now the instructor wants us to demonstrate that we can use a dynamically allocated array. For some reason when I do this, my output is an audible "beep" and a bunch of weird symbols. Can anyone spot what I'm doing wrong here?
In the first version, I manually initialized my array, like so:
But now I'm initializing it using a dynamic array (pointless in this case, I know. They just want to see that we can use it successfully) and a for-loop, like this:
1 2 3 4 5 6 7 8
int size = 9;
char *board = newchar[size];
for ( int i = 0; i < size; i++ )
{
board[i] = (i + 1);
}
To create the same array as in the first example. Everything compiles but I'm getting weird symbols instead of the numbers 1 through 9 on my game board. Here is the complete code:
#include <iostream>
usingnamespace std;
void displayCurrentBoard(char board[]);
int main()
{
int player = 1, size = 9;
char turn;
char *board = newchar[size]; // Creates array based on size specified
for ( int i = 0; i < size; i++ )
{
board[i] = (i + 1);
}
cout << "Welcome to the C++ edition of Tic-Tac-Toe!\n"
<< "Player 1 will be X's and Player 2 will be O's.\n";
displayCurrentBoard(board);
do
{
if (player == 1)
{
cout << "Player 1, please specify a position on the board: ";
cin >> turn;
for (int i = 0; i < 9; i++)
{
if (turn == board[i])
{
board[i] = 'X';
}
}
displayCurrentBoard(board);
player++; // Switches to Player 2's turn
}
if (player == 2)
{
cout << "Player 2, please specify a position on the board: ";
cin >> turn;
for (int i = 0; i < 9; i++)
{
if (turn == board[i])
{
board[i] = 'O';
}
}
displayCurrentBoard(board);
player--; // Switches to player 1's turn
}
} while (player > 0); // Arbitrary condition that is always true
return 0;
}
void displayCurrentBoard(char board[])
{
cout << endl;
for (int i = 0; i < 3; i++)
{
cout << board[i] << " ";
}
cout << endl;
for (int i = 3; i < 6; i++)
{
cout << board[i] << " ";
}
cout << endl;
for (int i = 6; i < 9; i++)
{
cout << board[i] << " ";
}
cout << endl << endl;
}