Mahmud Adam - 1 year ago 75
C++ Question

# 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
`checkRow`
and
`checkCol`
are the coordinates entered by the user.

``````if (jumpPosRightToLeft(board, 'R', 'B', row, col, checkRow, checkCol) ||
jumpPosRightToLeft(board, 'B', 'R', row, col, checkRow, checkCol)) {
cout << "Can Jump";
}

if (jumpPosLeftToRight(board, 'R', 'B', row, col, checkRow, checkCol) ||
jumpPosLeftToRight(board, 'B', 'R', row, col, checkRow, checkCol)) {
cout << "Can Jump";
}
``````

And here is how the methods are implemented:

``````bool jumpPosRightToLeft(char **board, char tokenA, char tokenB, int r, int c, int row, int col) {
if (board[row][col] == tokenA &&
board[row - 1][col + 1] == tokenB &&
board[row - 2][col + 2] == ' ') {
cout << "Piece can jump" << endl;
return true;
}
return false;
}

bool jumpPosLeftToRight(char **board, char tokenA, char tokenB, int r, int c, int row, int col) {
if (board[row][col] == tokenA &&
board[row + 1][col - 1] == tokenB &&
board[row + 2][col - 2] == ' ') {
return true;
}
return false;
}
``````

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download