【问题标题】:IndexOutOfRangeException on multi dimensional char array多维字符数组上的 IndexOutOfRangeException
【发布时间】:2014-06-22 10:02:34
【问题描述】:

代码循环遍历数组并将每个索引初始化为“*”。但是,我在Cave[i,j] 上收到了IndexOutOfRangeException,并希望得到一些指导。

char[,] Cave = new char[GridHeight, GridWidth];

    for (int i = 0; i < GridWidth; i++)
    {
        for (int j = 0; j < GridHeight; j++)
        {
            Cave[i, j] = '*'; //Error Here
        }
    }
  • 为了澄清GridHeightGridWidth声明如下

    public const int GridHeight = 5;

    public const int GridWidth = 7;

【问题讨论】:

  • 你真的应该学习如何使用调试器,相信我,它会让你的生活变得更加轻松
  • 按照惯例,宽度通常是第一个维度,高度是第二个维度。应用该规则,它应该很简单。

标签: c# arrays for-loop multidimensional-array indexoutofrangeexception


【解决方案1】:

您正在声明一个 5 x 7 数组,但随后尝试访问(例如)Cave[7,5],因为您的变量是向后的。

char[,] Cave = new char[GridHeight, GridWidth];  // declare 5x7 array

for (int i = 0; i < GridWidth; i++)        // range of i is 0 - 6
{
    for (int j = 0; j < GridHeight; j++)   // range of j is 0 - 4
    {
        Cave[i, j] = '*'; //Error Here     // try to access Cave[6,4] - oops!
    }
}

尝试交换它们:

char[,] Cave = new char[GridWidth, GridHeight];

如果对您更有意义,或者交换另一对:

char[,] Cave = new char[GridHeight, GridWidth];

for (int i = 0; i < GridHeight; i++)
{
    for (int j = 0; j < GridWidth; j++)
    {
        Cave[i, j] = '*';
    }
}

【讨论】:

    【解决方案2】:

    通常我们看待事物的方式和编译器的方式是不一样的。

    这是你的程序输出:

    int GridHeight = 10;
    int GridWidth = 5; 
    
    char[,] Cave = new char[GridHeight, GridWidth];
    
    for (int i = 0; i < GridWidth; i++)
    {
       for (int j = 0; j < GridHeight; j++)
       {
            Console.Write(i+","+ j +"   ");
          // Cave[i, j] = '*'; //Error Here
       }
        Console.WriteLine();
    }
    

    它输出:

    0,0   0,1   0,2   0,3   0,4   0,5   0,6   0,7   0,8   0,9   
    1,0   1,1   1,2   1,3   1,4   1,5   1,6   1,7   1,8   1,9   
    2,0   2,1   2,2   2,3   2,4   2,5   2,6   2,7   2,8   2,9   
    3,0   3,1   3,2   3,3   3,4   3,5   3,6   3,7   3,8   3,9   
    4,0   4,1   4,2   4,3   4,4   4,5   4,6   4,7   4,8   4,9   
    

    如您所见,第一个变量是实际宽度,而不是高度。所以要么重命名它们,要么交换它们:)

    每当您考虑二维数组(至少在控制台输出方面)时,请记住第一个轴是 X(从左到右,升序),第二个轴是 Y(向上向下,升序)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-19
      • 1970-01-01
      • 1970-01-01
      • 2018-03-05
      • 1970-01-01
      • 1970-01-01
      • 2013-05-01
      • 1970-01-01
      相关资源
      最近更新 更多