2017-11-04 40 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]、Iは、このエラーを提示しています:

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は "3"としてカウントされます。 – 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 ectではなくC#ではありません。

また、this SO threadをお読みください。