1
field = new int[input.Width][][];

for (int x = 0; x < input.Width; x++)
{
       field[x] = new int[input.Height][];

       for (int y = 0; y < 3; y++)
       {
           field[x][y] = new int[3];
       }
}

For some reason the above code is giving me out of range exception but the following works fine:

field = new int[input.Width][][];

for (int x = 0; x < input.Width; x++)
{
       field[x] = new int[input.Height][];

}

for (int y = 0; y < input.Height; y++)
{

       for (int x = 0; x < input.Width; x++)
       {
            field[x][y] = new int[3];                   

            field[x][y][0] = random.Next(0, output.Width);
            field[x][y][1] = random.Next(0, output.Height);
            field[x][y][2] = MaskFunctions.DSCALE;

        }
 }

Can anyone point out what am i doing wrong?

Also: Is there a difference between out of range and out of bound exception?

2
  • the first has y < 3, the second has y < input.Height. Do those values differ? Commented Oct 10, 2013 at 23:22
  • @ps2goat yes they do! but you see its 4:30 am here :) Commented Oct 10, 2013 at 23:36

1 Answer 1

4

Your inner loop goes from 0 to 3, instead of 0 to input.Height. This will produce an out of range exception when input.Height < 3.

You probably meant to do this:

field = new int[input.Width][][];

for (int x = 0; x < input.Width; x++)
{
       field[x] = new int[input.Height][];

       for (int y = 0; y < input.Height; y++)
       {
           field[x][y] = new int[3];
       }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! it worked! can you also tell me if there is a difference between out of range and out of bound exception?
@AliZahid There's no difference, at least in this context. Some people just prefer to use different language. .NET calls it IndexOutOfRangeException but Java calls it an an ArrayIndexOutOfBoundsException. In either case, they mean essentially the same thing.

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.