MBrazier4
MBrazier4

Reputation: 45

How to avoid index outside of bound of the array?

I'm making an Othello/Reversi game where I use a 2d array to hold the memory for each space on the board.

In order to check for valid moves i'm using an if statement where I use r+1 in order to check the next space along on the same row. However as the array is only [8, 8] large, when I encounter a situation where r is 8 I get an error because it is trying to check the 9th element in the array. This gives me an index out of bounds error.

Was wondering what the best way to fix this would be? I thought maybe swapping to a list but i'm unsure if that will work as well for a 2d array?

public box[,] grid = new box[8, 8];

if ((grid[r + 1, c].value == currentPlayer)
        {
            return true;
        }

Upvotes: 1

Views: 4909

Answers (1)

ChrisF
ChrisF

Reputation: 137148

You just have to check that r + 1 is a legal index. Having a list won't help as you'll still be checking beyond the bounds of the list. So you simply need:

if (r + 1 > 7) return false;

as you know the size of your array. However to avoid "magic numbers" you'd be better off getting the upper bound of the first dimension of the array:

if (r + 1 > grid.GetUpperBound(0)) return false;

You can do the same for checking that c is within bounds:

if (c < 0 || c > grid.GetUpperBound(1)) return false;

Upvotes: 2

Related Questions