简体   繁体   English

在c#中初始化锯齿状数组会使索引超出范围异常

[英]Initializing a jagged array in c# gives index out of range exception

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? 另外:超出范围和出界异常之间是否存在差异?

Your inner loop goes from 0 to 3 , instead of 0 to input.Height . 你的内部循环从0变为3 ,而不是0input.Height This will produce an out of range exception when input.Height < 3 . 输入时,这将产生超出范围的异常。 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];
       }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM