Really Weird Character Array Output

Hey guys,
So I'm doing a simple tictactoe class and one of the functions in the class is printBoard. Now I'm using a char array to fill up the board and do all the calculations. The array is 2D, and my constructor is as follows:

1
2
3
4
5
tictactoe::tictactoe()
{
	char spaces[3][3] = {0};
	int currentPlayer = 1;
}


My printBoard function is this:

1
2
3
4
5
6
	cout << spaces[0][0] << "||" << spaces[0][1] << "||"<< spaces[0][2] << endl;
	cout << "========" << endl;
	cout << spaces[1][0] << "||" << spaces[2][1] << "||"<< spaces[1][2] << endl;
	cout << "========" << endl;
	cout << spaces[2][0] << "||" << spaces[2][1] << "||"<< spaces[2][2] << endl;
	cout << endl;


Now I know the board isn't that pretty I'm just testing to make sure everything is working. Now my question is; when I print he board using the function I get a strange output from the console. At first I thought it was because the array was initialized to NULL and that was the output for it, but then I copied my print function and placed the code from the function straight after the constructor so it looked like this:

1
2
3
4
5
6
7
8
9
10
11
tictactoe::tictactoe()
{
	char spaces[3][3] = {0};
	int currentPlayer = 1;
	cout << spaces[0][0] << "||" << spaces[0][1] << "||"<< spaces[0][2] << endl;
	cout << "========" << endl;
	cout << spaces[1][0] << "||" << spaces[2][1] << "||"<< spaces[1][2] << endl;
	cout << "========" << endl;
	cout << spaces[2][0] << "||" << spaces[2][1] << "||"<< spaces[2][2] << endl;
	cout << endl;
}


This outputs the board with empty spaces where they should be, but the print function, which I run straight after the constructor, outputs these weird squiggles which I can't describe where the spaces should be. I'm really confused why as to why it is working intermittently. Could someone please shed some light on this for me?

Thanks
Could you show the code where you create the tictactoe object and calls the print function.
Sure thing, it's just this:

1
2
3
4
5
6
7
8
int main()
{
tictactoe gameBoard;
gameBoard.printBoard();

system("PAUSE");
return 0;
}
hmm, I see nothing wrong there.
Maybe it's just a bug. I have initialized the array using for loops and it has worked out fine. It just kinda annoyed me that one way worked and the other didn't even though they both should have worked :(
Look closely at this snippet:
1
2
3
4
5
tictactoe::tictactoe()
{
	char spaces[3][3] = {0};
	int currentPlayer = 1;
}


Do you realize that you are creating new instances of these variables that go out of scope when the function ends?

Topic archived. No new replies allowed.