初級 › Index was outside the bounds of the array の原因と直し方 › パターン2
Index was outside the bounds of the array の原因と直し方
配列やリストの範囲外アクセスで実行時に発生します。
1 class Program { 2 static void Main(string[] args) { 3 int[] nums = { 10, 20, 30 }; 4 for (int i = 0; i __ nums.Length; i++) { ^ 5 System.Console.WriteLine(nums[i]); 6 } 7 } 8 }
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Program.Main(String[] args) in Program.cs:line 5
空欄を埋めてビルドを通す
ループの継続条件が<=だと、末尾を1つ超えたインデックスまでアクセスしてしまいます。
次の問題