Skip to main content
GameDev.net gamedev.net
🔒 Locked

Why am I getting this IndexOutOfRangeException?

Started by ysg May 7, 2013 at 3:07 AM 4 replies 1.4k views
Original Post
ysg
ysg
Hi, this is my code.
public Matrix GetCol (int col)
{
  if (col > this.Cols)
  {
    throw new System.Exception("Can't get column #" + col
      + " because it's greater than the number of columns " + this.Cols
      + ".");
  }

  double [,] newMatrix = new double[this.Rows, 1];

  for (int row = 0; 0 < this.Rows; row++)
  {
    newMatrix[row, 0] =  // HERE!!!!
      this.matrix[row, col];
  }

  return new Matrix(newMatrix);
}
I traced my code and on the line indicated, I get an System.IndexOutOfRangeException. This... makes zero sense. This is a single-threaded application and this.Rows is not being modified. So why is there an exception in there?
ysg
ysg
The weird thing, is that while I'm tracing the code, when row is being incremented and it becomes 4, it _still_ goes into the loop and then tries to go to newMatrix[4, 0], which makes sense that I'm getting the exception.

But what doesn't make ANY sense is the fact that it's getting into the loop body after row is equal to 4. At that point, the loop should have stopped long ago.

[edit]

Never mind, 0 < this.Rows is just stupid smile.png .
Nypyren
Nypyren

0 < this.Rows

row < this.Rows

Dave Hunt
Dave Hunt

Um... "0 < this.Rows"??? That should be "row < this.Rows".

edit -- tooo slooooow

ysg
ysg

Um... "0 < this.Rows"??? That should be "row < this.Rows".

edit -- tooo slooooow

Yeah smile.png .
evolutional
evolutional

Also, if you're using zero-based arrays then you need to check that col >= this.cols at the top, as if cols = 1, the max offset you can use is actually zero.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.