[英]Getting “Index was outside the bounds of the array” exception and I'm not sure why
[英]Why is the index out of bounds of the array when I'm resizing the array?
这是我正在研究的程序的一小部分。 我试图通过创建另一个数组,将所有内容从第一个数组复制到第二个数组,然后让第一个数组引用第二个数组来手动调整数组的大小。
RoundInfo[] rounds = new RoundInfo[10];
int numRounds = 0;
RoundInfo ri;
RoundInfo[] newRI;
public void AddRound(int height, int speed)
{
if (numRounds >= rounds.Length) // creates a new array of RI objects if numRounds is greater than rounds.Length
{
newRI = new RoundInfo[numRounds + 1];
// Console.WriteLine("numRounds: {0} length: {1}", numRounds, rounds.Length); // me checking if the AddRound correctly increments numRounds, it does.
//Console.WriteLine(newRI.Length);
for (int i = 0; i < newRI.Length; i++)
newRI[i] = rounds[i]; // *THE PROGRAM CRASHES HERE*
rounds = newRI;
ri = new RoundInfo(height, speed);
rounds[numRounds] = ri;
numRounds++;
}
if (numRounds < rounds.Length) // the program goes through this fine
{
ri = new RoundInfo(height, speed);
rounds[numRounds] = ri;
numRounds++;
}
}
我不明白如果新数组更长的话为什么会崩溃。
因为当numRounds == rounds.Length时,您要先输入。 其中10 == rounds.Length(是10)
然后添加
if (numRounds >= rounds.Length) // here you're having numRounds as 10
{
newRI = new RoundInfo[numRounds + 1]; //here you're adding + 1 will get newRI = new RoundInfo[11]
for (int i = 0; i < newRI.Length; i++)
newRI[i] = rounds[i]; // *THE PROGRAM CRASHES HERE*
// so in here your program will crash due to indexOutOfBOunds because newRI[11] = rounds[11];
//rounds[11] is not existing
rounds = newRI;
ri = new RoundInfo(height, speed);
rounds[numRounds] = ri;
numRounds++;
}
您可以通过不在newRI上添加+1来防止这种情况
if (numRounds >= rounds.Length)
{
newRI = new RoundInfo[numRounds]; //remove +1 here
//etc codes
}
我不知道你这部分打算
//如果numRounds大于rounds,则创建一个新的RI对象数组。
复制数组但超过先前的数组长度是不可能的。 看来您正在尝试做(newArray [oldArray.Length + 1] == oldArray [oldArray.Length]),因为它确实超出了您的范围。
newArray [11]不能具有oldArray [11],因为它不存在
您可以尝试的是oldArray的长度,而不是new
for (int i = 0; i < rounds.Length; i++)
newRI[i] = rounds[i];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.