3

I'm trying to create a 2D char array to hold a grid of chars which will be used as a sort of 'map' for a 2D console game.

I am getting a:

IndexOutOfRange exception

..and cannot see why. I've stepped through the code in debug mode and still cannot see the issue.

It steps through the code fine until it hits X = 25 and Y = 1, the upper right boundary of my grid.

I have _gameWidth and _gameHeight created as follows, outside of main but still inside the class:

static int _gameWidth = 25;
static int _gameHeight = 15;

Following is the code that fails, when trying to generate and populate the grid. It fails at this point:

else if (x == _gameWidth && y == 1)
    _grid[x, y] = '╕';



static void GenerateGrid()
{
    for (int y = 1; y <= _gameHeight; y++)
    {
        for (int x = 1; x <= _gameWidth; x++)
        {
            if (x == 1 && y == 1)
                _grid[x, y] = '╒';
            else if (x == _gameWidth && y == _gameHeight)
                _grid[x, y] = '╛';
            else if (x == _gameWidth && y == 1)
                _grid[x, y] = '╕';
            else if (x == 1 && y == _gameHeight)
                _grid[x, y] = '╘';
            else if ((x != 1 && y == _gameHeight) || (x != _gameWidth && y == 1))
                _grid[x, y] = '═';
            else if ((x == 1 && y > 1 && y < _gameHeight) || (x == _gameWidth && y > 1 && y < _gameHeight))
                _grid[x, y] = '│';
            else
                _grid[x, y] = 'x';

        }
        Console.WriteLine("");
    }
}
2
  • 1
    We're missing the declaration of grid[,] Commented Sep 26, 2015 at 11:51
  • Problem solved. Thanks for fast replies. Commented Sep 26, 2015 at 12:03

2 Answers 2

5

Change

for (int i = 1; i <= gameHeight; i++)

to

for (int i = 0; i < gameHeight; i++)

and do the same for width.

EDIT: This is because array indexes start at the number 0 and end with the length of the array minus 1.

Sign up to request clarification or add additional context in comments.

1 Comment

I love that despite the other one being chosen as the correct answer, this answer has more votes :p
3

This exception means that you have accessed an invalid index. From the way you have written the loop I can tell that you think that indexes go from 1 to the length of the array. Arrays are zero-based, though. Use the standard loop form:

for (int i = 0; i < length; i++)

Your loop starts at one. You can use the Visual Studio for loop template. Just type "for<tab><tab>".

Your program might benefit from the Code Review Stack Exchange site.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.