C++ Tic tac toe program -


i writing tic-tac-toe program pretty basic c++ course , have problem that's stumped me bit.

below code usermove() function takes input user , writes 'x' char array board[2][2]. works of time, problem if user inputs row = 1 column = 0, both board[1][0] , board[0][2] changed 'x'.

does see why happening?

//! function usermove(). /*!  function usermove() takes 2 integer inputs terminal user,  checks see if move valid one, , updates char array board.  */ void usermove() //take player's move {    //! int row stores user's first integer input.    int row;    //! int column stores user's second integer input.    int column;     cout << "enter row you'd x:";    cin >> row;    cout << "enter column you'd x:";    cin >> column;      //! if statement checks user has selected blank space     //! next move.  if space taken, user informed     //! error message , usermove() function called     //! recursively.    if(board[row][column] == ' ')    {       board[row][column] = 'x';    }    else    {       cout << "invalid move\n";       this->usermove();    } } 

your dimensions wrong. array dimensions count elements, instead of denoting highest index:

char board[3][3];  /**  * may access following:  *  *   board[0][0]  *   board[0][1]  *   board[0][2]  *   board[1][0]  *   board[1][1]  *   board[1][2]  *   board[2][0]  *   board[2][1]  *   board[2][2]  */ 

with board[2][2], have fewer elements think, , when try things getting value of non-existent element board[0][2], may just happen value of board[1][0] instead (due how memory accesses work, , how arrays laid out in memory) — that's why think write occurring on both of these elements.


Comments

Popular posts from this blog

php - render data via PDO::FETCH_FUNC vs loop -

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

The canvas has been tainted by cross-origin data in chrome only -