Mahmud Adam
Mahmud Adam

Reputation: 3579

Checking neighboring diagonal positions in 2D Array

I have a 2D array setup to store game-pieces in a checker board, and I have create methods that allow me to check to see if the piece at the selected location can make a jump. Each method works on its own, but when I try to use them together --specifically the one that checks southwest direction--I get Access violation reading location error. I haven't yet figure out how to check if I am going out of bounds, but I don't think that is the issue here. row and col are the height and width of the array and r and c are the coordinates entered by the user.

if (jumpPosRightToLeft(board, 'X', 'O', row, col, r,c) ||
    jumpPosRightToLeft(board, 'O', 'X', row, col, r,c)) {
    cout << "can make move";
}

if (jumpPosLeftToRight(board, 'X', 'O', row, col, r, c) ||
    jumpPosLeftToRight(board, 'X', 'O', row, col, r, c)) {
    cout << "can make move";
}

And here is how the methods are implemented:

bool jumpPosRightToLeft(char **board, char x, char y, int row, int col) {
    if (board[row][col] == x &&
        board[row - 1][col + 1] == y &&
        board[row - 2][col + 2] == ' ') {

        return true;
    }
    return false;
 }

bool jumpPosLeftToRight(char **board, char x, char y, int row, int col) {
    if (board[row][col] == x &&
        board[row + 1][col - 1] == y &&
        board[row + 2][col - 2] == ' ') {
        return true;
    }
    return false;
}

Upvotes: 0

Views: 587

Answers (1)

Sebastian Lenartowicz
Sebastian Lenartowicz

Reputation: 4854

You are, indeed, going out-of-bounds.

What you should do is something like this:

#define BOARDSIZE 8 // Define whatever board size (square) you want here

bool jumpPosLeftToRight(char **board, char tokenA, char tokenB, int r, int c, int row, int col) {
    if (row + 1 >= BOARDSIZE || row + 2 >= BOARDSIZE || col - 1 < 0 || col - 2 < 0) return false;

    if (board[row][col] == tokenA &&
        board[row + 1][col - 1] == tokenB &&
        board[row + 2][col - 2] == ' ') {
        return true;
    }
    return false;
}

I'm certain you can extrapolate it to your other functions easily enough. When working with stuff like arrays, you should always bounds-check before attempting to operate on them.

Upvotes: 1

Related Questions