索引超出范围异常的数组[重复](Index out of range exception on array [duplicate])
这个问题在这里已有答案:
什么是IndexOutOfRangeException / ArgumentOutOfRangeException以及如何解决它? 3个答案我正在尝试反转数组。 这是我的代码:
using System; class Hello { static void Main() { int[] num = new int[] { 1, 2, 3, 4, 5 }; int index = num.Length - 1; int[] newNum = new int[index]; for (int i = 0; i < num.Length; i++) { newNum[i] = num[index]; // error index--; Console.WriteLine(newNum[i]); } Console.ReadLine(); } }当我运行代码时,控制台打印
5 4 3 2然后返回一个错误:
IndexOutOfRangeException未处理
在线上:
newNum[i] = num[index];这行代码有什么问题? 当我在for循环之前打印num[0]它工作正常。
This question already has an answer here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it? 4 answersI'm trying to reverse an array. This is my code:
using System; class Hello { static void Main() { int[] num = new int[] { 1, 2, 3, 4, 5 }; int index = num.Length - 1; int[] newNum = new int[index]; for (int i = 0; i < num.Length; i++) { newNum[i] = num[index]; // error index--; Console.WriteLine(newNum[i]); } Console.ReadLine(); } }When I run the code, the console prints
5 4 3 2and then returns an error:
IndexOutOfRangeException was unhandled
on the line:
newNum[i] = num[index];What's wrong with that line of code? When I print num[0] before that for loop it works fine.
最满意答案
你的新阵列的长度是4.这意味着我将从0到3覆盖
int[] newNum = new int[index];你的循环将变为i = 4
当我将4你的代码将崩溃。 因为newNum仅支持第3个索引。
这应该是
int[] newNum = new int[index+1];length of your new array is 4. that's mean I'll cover from 0 to 3
int[] newNum = new int[index];and your loop will go i=4
when i will 4 your code will collapse. as newNum support only to 3rd index.
this should be
int[] newNum = new int[index+1];更多推荐
发布评论