I am working on a chess game in c++ . I have the classes :
class piece
{
protected :
point position ;
char represent ;
bool colour; // true for player 1 = green , false for player 0 = blue
public :
virtual ~piece() ;
bool find_player(piece* to_check, int num);
char get_char() ;
bool get_colour() ;
virtual bool move_setup(point source, point dest, piece* arr[][SIZE] ) = 0 ;
virtual bool move(point source, point dest, piece* arr[][SIZE]) = 0;
bool same_player(point dest, piece* arr[][SIZE], int* num);
};
class board
{
private:
piece* arr[SIZE][SIZE] ;
public :
board();
void free_borad();
void set_piece(int x , int y , int type , bool colour );
void print_board();
void move(point source , point dest);
void set_colour(int i , int j , bool reset );
};
class pawn : public piece
{
public :
pawn(point position , bool colour );
~pawn();
virtual bool move_setup(point source, point dest, piece* arr[][SIZE]);
virtual bool move(point source, point dest, piece* arr[][SIZE]);
bool if_forward(point source, point dest);
bool if_diagonal(point source, point dest, int* offset);
};
I have a class for every piece in which I have implemented the move functions. the classes are not relevant so I just put a pawn class for the example . the board move function :
void board::move(point source, point dest)
{
if (arr[source.get_x()][source.get_y()]) // if not empty
{
int x = source.get_x(), y = source.get_y() ;
if (arr[x][y]->move_setup(source, dest, arr ) ) // if the piece can move there
{
delete arr[dest.get_x()][dest.get_y()];
arr[dest.get_x()][dest.get_y()] = arr[source.get_x()][source.get_y()];
arr[source.get_x()][source.get_y()] = NULL;
std::cout << " Succes! " << std::endl;
}
else
{
// error
}
}
else // empty
{
// error
}
}
my program crashes at the line
if (arr[x][y]->move_setup(source, dest, arr ) )
I have debbuged it using the VS debugger , and realized that the crash occurs when sending the array , error message :
Access violation reading location 0xFFFFFFFF.
I have tried to send it in many different ways , and nothing works , but this method is exactlly how a friend of mine did it , and it works just fine for him . can anyone help ? thank you .
Arrays in C++ are 0-based, which means the index of the first element is 0. If your coordinates are 1-based, it means you are accessing an element one row and one column off in the array. That in turn leads to breaching the bounds of the array and your crash. The solution is either to adopt a 0-based coordinate system or subtract 1 from the x/y coordinates when accessing the array.