Dynamically Allocated Array

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:

 
char board[9] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};


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 = new char[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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <iostream>

using namespace std;

void displayCurrentBoard(char board[]);

int main()
{
	int player = 1, size = 9;
	char turn;

	char *board = new char[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;
}
char *board = new char[size] { '1', '2', '3', '4', '5', '6', '7', '8', '9' }; // C++11

Or:
1
2
3
4
5
6
char *board = new char[size] ; // legacy C++

for ( int i = 0; i < size; i++ )
{
    board[i] = (i + 1) + '0' ; // 7 + '0' == '7' etc
}
Thanks! I never would have been able to figure out the " + '0' " bit. Works great now.
Topic archived. No new replies allowed.