So I was working on a Tic-Tac-Toe game and for my input function I was getting the move the player made to store as an integer in a 2d array, the input is gotten using a reference to a 1D array of pointers to positions in the 2D array.
However my problem is, when I seem to set the value of the multi-dimensional array’s square to something by using a pointer, nothing happens.
Here is the input function:
void Game::input(Board b){
int *spots[9]; // Possible spots for the input
bool validInput = false;
spots[0] = &b.board[2][0];
spots[1] = &b.board[2][1];
spots[2] = &b.board[2][2];
spots[3] = &b.board[1][0];
spots[4] = &b.board[1][1];
spots[5] = &b.board[1][2];
spots[6] = &b.board[0][0];
spots[7] = &b.board[0][1];
spots[8] = &b.board[0][2];
redo:
cout << ">> " << endl;
int input; // Input
cin >> input; // Get the input
validInput = cin;
if(!validInput){
cout << "Numbers only please!" << endl;
cin.clear();
while(cin.get() != '\n');
goto redo;
}
if(input > 9 || input <= 0){
cout << "Invalid move!" << endl;
goto redo;
}
input--; // Subtract 1 for array location
if(*spots[input] != 0){
cout << "Square is already being used!" << endl;
goto redo;
}
*spots[input] = 1;
}
Now, say I input the number 7. It should set b.board[0][0] to 1. However this doesn’t seem to happen. When I run a unit case afterwards, the board[0][0] doesn’t seem to be set to 1, and it doesn’t reflect in my array. Am I messing something up about pointers here?
The argument to your function is passed by value and therefore any changes you make to it are not recognized since pass by value creates a copy of the argument. Consider passing by pointer or reference instead.