Question

I'm having trouble with classes for a C++ program of a game of Reversi. Basically my problem is trying to get a 2D array (which is a private class variable) to update after exiting a function. The array is declared as a private variable of class Board as seen below: (MAX_SIZE = 10, but the array size is controlled by the 1st argument in the main.)

private:
//array variable for the board
char Board[MAX_SIZE][MAX_SIZE];
int BoardSize;
};

Here is where I create the board, setting it to all dashes to start. I debugged it with the cout to verify that it works correctly and it does.

void Board::CreateBoard(){
char Board[BoardSize][BoardSize];

//Sets the board to be all dashes
for (int i=0; i < BoardSize; i++){
 for (int j=0; j < BoardSize; j++){
  Board[i][j] = '-';
  cout << Board[i][j] << " ";
  }
 }
}

Here is the printBoard function, which when called simply prints gibberish. I suspect it is because the board is reverting back to its previous state after the CreateBoard() function ends.

void Board::PrintBoard(){
//Prints out the array board
for(int i=0;i < BoardSize;i++){
for(int j=0;j < BoardSize;j++){
  cout << Board[i][j];
  }
 }
}

I'm new to C++ and classes, and don't really understand pointers and such. How can I get the board to update and stay that way between functions? Any feedback would be appreciated, thank you!

Was it helpful?

Solution

Inside
void Board::CreateBoard()
you have declared a local variable char Board[BoardSize][BoardSize] that you are fillng with -.
But in your
void Board::PrintBoard()
I think you are calling the char Board[MAX_SIZE][MAX_SIZE] defined in the class.

So, you are setting a local variable and printing the class variable that you have not set, hence the weird output.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top