Search code examples
c++multidimensional-arraytic-tac-toe

Initializing an array works fine, but when trying to print it back out it prints an extra column and an unexpected character


So this compiles without a problem. The problem I'm having is that when it prints to the console, there is an extra column and a strange ascii character in the lower right corner. If I try to lessen the size of the array, I can't initialize it with 9 elements anymore- and I have to have nine elements to make it a tic tac toe board. I thought it was an off by one error, but if so, I can't figure out how to fix it. I've read quite a few of the "tic tac toe" similar questions, but they don't seem to be having the same issue.

#include <iostream>

using namespace std;

int main ()
{
int countrow, countcol, play=1, subscript1, subscript2;
int ARRAY_ROWS = 3, ARRAY_COLS =3;
char board [3][3] = {{42, 42,42}, {42, 42,42}, {42, 42,42}};
char input;
while(play>0)
{
    for(countrow = 0; countrow<ARRAY_ROWS; countrow++)
    {
        for(countcol=0; countcol<ARRAY_COLS; countcol++)
        {
            cout<<board [countrow][countcol];
        }
        cout<<board[countrow][countcol];
        cout<<endl;
    }
cout<<"Player 1, enter your mark using a row column coordinate system.\n";
cin>>subscript1>> subscript2;
subscript1+=1;
board[subscript1][subscript2] = 88;
cout<<"Player 2, enter your mark using a row column coordinate system.\n";
cin>>subscript1>> subscript2;
board[subscript1][subscript2] = 79;
}
system("pause");
return 0;
}

Solution

  • Here is the problem:

    for(countrow = 0; countrow<ARRAY_ROWS; countrow++)
    {
        for(countcol=0; countcol<ARRAY_COLS; countcol++)
        {
            cout<<board [countrow][countcol];
        }
        cout<<board[countrow][countcol]; 
        //^^^^^This one is redundant and you are accessing invalid memory block
        //^^^^^^ countcol is out of bound
        cout<<endl;
    }