poke
poke

Reputation: 2982

IndexOutOfRangeException when trying to access array element

I can't figure out why I'm getting the out of range exception on the following piece of code. The values for _maxRowIndex and _maxColIndex are 5, and 0 respectively. The exception is being thrown on the first time through when row and col are both equal to 0. I don't understand why 0, 0 would be out of bounds on the array.

    _cells = new ToolBarButton[_maxRowIndex, _maxColIndex];
    .
    .
    .
    for (int col = 0; col <= _maxColIndex; col++) {
                    for (int row = 0; row <= _maxRowIndex;  row++)
                    {

                      if (_cells[row, col] == null)
                        {
                           PopulateCell(toolBarbutton, row, col);
                        }

                    }
                }

Upvotes: 1

Views: 154

Answers (4)

gangakinarewala
gangakinarewala

Reputation: 11

I guess you should declare _cells as below

_cells = new ToolBarButton[5,1];

instead of

_cells = new ToolBarButton[5,0];

Upvotes: 1

Tim Joseph
Tim Joseph

Reputation: 199

You have <= in your for statement...

So your loop evaluates for col =0, 1, 2, 3, 4 and 5... 5 is out of bounds

Upvotes: 1

jtdubs
jtdubs

Reputation: 13963

If you want the max index to be 5, that means the array needs to be of length 6 as the first element is at index 0.

So, change:

_cells = new ToolBarButton[_maxRowIndex, _maxColIndex];

to:

_cells = new ToolBarButton[_maxRowIndex+1, _maxColIndex+1];

Upvotes: 1

Mamta D
Mamta D

Reputation: 6450

Array indices start from 0 and are upto [upperbound-1]. Since your loop starts at 0, it must end at < the limit value rather than <= limit value. So, change the "<=" to "<" in the loop. Eg:

col <= _maxColIndex

should be changed to

col < _maxColIndex

Upvotes: 4

Related Questions