【问题标题】:Why is the index out of bounds of the array when I'm resizing the array?为什么在调整数组大小时索引超出数组范围?
【发布时间】:2017-06-15 03:30:37
【问题描述】:

这是我正在开发的程序的一小部分。我试图通过创建另一个数组来手动调整数组的大小,将第一个数组中的所有项目复制到第二个数组中,然后让第一个数组引用第二个。

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++;
            }

        }

如果新数组更长,我不明白为什么它会崩溃。

【问题讨论】:

  • newRI 可以去newRI.Length 但不是旧的。 List&lt;T&gt; 不需要这些,即使您“不得不”使用数组,也有 Array.Copy

标签: c# arrays indexing resize indexoutofboundsexception


【解决方案1】:

因为当 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.Length,则创建一个新的 RI 对象数组

复制一个数组但超出之前的数组长度是不可能的。看来您正在尝试做 (newArray[oldArray.Length + 1] == oldArray[oldArray.Length]) 你不能这样做,因为它真的会越界。

newArray[11] 不能有 oldArray[11] 因为它不存在

你可以尝试的是 oldArray 的长度,而不是新的

for (int i = 0; i < rounds.Length; i++)
            newRI[i] = rounds[i]; 

【讨论】:

  • 谢谢!我能够修复它!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多