数组上的索引超出范围异常
本文关键字:范围 异常 索引 数组 | 更新日期: 2023-09-27 18:25:25
我正在尝试反转一个数组。这是我的代码:
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];
那行代码出了什么问题?当我在循环之前打印num[0]
时,它工作得很好。
新数组的长度为4。这意味着我将覆盖从0到3的
int[] newNum = new int[index];
你的循环将进行i=4
当我将4你的代码将崩溃。因为newNum只支持第三个索引。
这应该是
int[] newNum = new int[index+1];