Home > database >  How do I stop segmentation error with array in C ?
How do I stop segmentation error with array in C ?

Time:11-24

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.

CodePudding user response:

void print_board(string board[3][3])

why are you using a string[3][3] ? you basically just need a 3x3 character array


string turn(string board[3][3], bool xturn)

in the above function, you seem to only able to put values in {0,0},{1,1},{2,2} since you use position for both x and y. you need to let user enter both x and y


board[(int)floor(position / 3)][(position % 3) - 1] = "X";

make sure you keep yourself in range 0..2, -1 is outside and will cause undefined behavior


return board[3][3];

No that is wrong in more ways than one, and in any case there is no need to return a copy


board[3][3] = turn(board, xturn);

this will not go well, you return a board of 3x3 strings but assign it to at best, an undefined place.

since you already pass the address of the board to your turn function, that is that is all needed. change it in place.


turn(board, xturn);   

arrays are addresses in memory, it is the starting address where in memory some data is stored

if you pass an array/matrix to a function you are letting the function know where in memory it is stored, so any changes to the array/matrix will be done in place, therefore you do not need to return a copy.

  •  Tags:  
  • c
  • Related