0

I am obviously a beginner and I have the error that says check runtime error #2 - stack around variable 'game' was corrupted.

I am trying to have my board initialized in a separate function so I am able to change the board based off of input. This is why I have two functions to do this. I don't understand why, could anyone help?

#include <iostream>
using namespace std;

class ticTacToe
{
private:
    char board[3][3];

public:
    void initiate();
    void postboard();
};

int main()
{
    ticTacToe game;
    game.initiate();
    game.postboard();
}

void ticTacToe::initiate()
{
    board[3][3] = '0';
    int n = 1;

    for (int x=0; x<3; x++)
    {
        for (int y=0; y<3; y++)
        {
            board[x][y] = '0' + n++;
        }
    }           
}

void ticTacToe::postboard()
{
    for (int x=0; x<3; x++)
    {
        for (int y=0; y<3; y++)
        {
            cout << " " << board[x][y] << " ";
        }
        cout << endl;
    }
}
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218

1 Answers1

0

You cannot do this

board[3][3] = '0';

You are trying to assign the char '0' to the element [3][3] of board, but the only valid indexes of board are [0] to [2]

You also cannot do

board[x][y] = '0' + n++;

because it will result in undefined behavior

Community
  • 1
  • 1
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218