So I am trying to learn about classes in C++ (I usually write Python) and I am getting some strange behavior from the following code which will be a dynamically sizing game of Tic Tac Toe:
#include <iostream>
#include <string>
// Square NxN board, win with N consecutive.
class TicTacToe {
public:
void PrintBoard();
void MakeMove(int p, int l);
void checkMove(int &position);
bool isWinner() const;
void checkPlayer(int &number, char &move);
TicTacToe(int s);
private:
int player;
int location;
int size;
int **board;
};
void TicTacToe::PrintBoard() {
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
std::cout << board[i][j] << ' ';
}
std::cout << std::endl;
}
}
TicTacToe::TicTacToe(int s) {
size = s;
board = new int * [size];
if (board) {
for(int i = 0; i < size; ++i) {
board[i] = new int [size];
assert(board[i]);
}
}
}
int main(int argc, char **argv) {
TicTacToe game(3);
TicTacToe Game(5);
game.PrintBoard();
Game.PrintBoard();
return 0;
}
The code seems to be working properly, and properly allocating the size of the 2d arrays that represent the game boards. However, the values that are printing are a bit weird. I was hoping someone could explain why I am getting the following output:
0 536870912 0
0 536870912 0
0 536870912 0
0 536870912 0 536870912 10
0 536870912 0 536870912 8
0 536870912 0 536870912 6
0 536870912 0 536870912 4
0 536870912 0 536870912 2
My question mainly is why are the odd indexes of the array printing as '536870912' and not '0' and also why are there 10, 8, 6, 4, 2 in the final column of the second array? Am I doing something wrong? Is there a better way to allocate the board sizes? Any help is appreciated.