I am creating a simple command line, tic-tac-toe game in C++. Whenever I reun the code I get no compiler errors but then VSCode tells me once I have given input that there is a Segmentation Fault. I will paste my code below:
#include <iostream>
#include <cmath>
using namespace std;
void print_board(string board[3][3])
{
cout << " | | " << endl;
cout << " " << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << " " << endl;
cout << "_____|_____|_____" << endl;
cout << " | | " << endl;
cout << " " << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << " " << endl;
cout << "_____|_____|_____" << endl;
cout << " | | " << endl;
cout << " " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << " " << endl;
cout << " | | " << endl;
}
string turn(string board[3][3], bool xturn)
{
int position;
cout << "Where would you like to go (1 - 9): ";
cin >> position;
if (xturn)
{
string player_turn = "X";
}
else
{
string player_turn = "O";
}
board[(int)floor(position / 3)][(position % 3) - 1] = "X";
return board[3][3];
}
int main(void)
{
string board[3][3] = {{" ", " ", " "}, {" ", " ", " "}, {" ", " ", " "}};
bool xturn = true;
while (true)
{
print_board(board);
board[3][3] = turn(board, xturn);
xturn = !xturn;
}
return 0;
}
Any help is much is much appreciated. Thanks! If it helps I am using the GCC compiler.
(position % 3) - 1?-1is not a valid indexreturn board[3][3];accesses out of boundsreturn board[3][3];goes out of array bounds, no matter what.if (xturn) { string player_turn = "X"; ...has no effect whatsoever. You need to write less code and test more. This code has more than 1 problems