2017-11-04 98 views
0
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace ConsoleApp 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      // Changed from *int[,] matrix = new int[2, 2];* 
      int[,] matrix = new int[3, 3]; 
      // Still getting error with "[3,3]" 

      matrix[0, 0] = 1; 
      matrix[0, 1] = 2; 
      matrix[0, 2] = 3; 

      matrix[1, 0] = 4; 
      matrix[1, 1] = 5; 
      matrix[1, 2] = 6; 

      matrix[2, 0] = 7; 
      matrix[2, 1] = 8; 
      matrix[2, 2] = 9; 

      Console.Write(matrix[0, 2]); 

      Console.ReadKey(); 
     } 
    } 
} 

这是通过命令行执行的基本程序。多维数组:“索引超出了数组的范围。”

在运行,而不是显示存储在数组中的数字“3” [0,2],我带有此错误:

System.IndexOutOfRangeException:“指数阵列的边界之外“。

+0

它应该是'new int [3,3];',这里的数字表示每个维度的长度。 –

+0

你可能想看看这个:https://stackoverflow.com/questions/3814145/how-can-i-declare-a-two-dimensional-string-array –

+0

我正在阅读的书给我的印象是阵列从零开始向上计数,因此0,1,2将计为“三”。 – Jojo

回答

0

“new int [2,2];”意味着矩阵是2 x 2. 您正在通过矩阵[0,2]访问第3列,因此是例外。

0

@josias int[,] matrix = new int[2, 2];显示您有一个2行2列的矩阵。但是在你的代码中,你分配了3行3列的值。如果你有这样的值,请使用下面的代码。

int[,] matrix = new int[3, 3];

+0

我以为我们从零开始计数? – Jojo

+0

我更新了原文。我已经改为3 * 3矩阵,仍然出现“外界”的错误 – Jojo

0

这是直接从C# Specifications

Each dimension of an array has an associated length which is an integral number greater than or equal to zero. The dimension lengths are not part of the type of the array, but rather are established when an instance of the array type is created at run-time.

现在这是回答你的问题的一部分:

The length of a dimension determines the valid range of indices for that dimension: For a dimension of length N, indices can range from 0 to N - 1 inclusive.

因此,在您的案件的范围将是0到2 - 1其中0和1.在一些语言如VB.NET中,你的假设是corr但不在C#中。

另请参阅this SO thread