Reputation: 25
Here's a small piece of the program I am working on. I am trying to manually resize the array by creating another array, copying all of the items from the first array into the second and then having the first array refer to the second.
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++;
}
}
I don't see why it crashes if the new array is longer.
Upvotes: 0
Views: 212
Reputation: 1674
because you're entering in first if when numRounds == rounds.Length. where 10==rounds.Length(which is 10)
theng adding on
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++;
}
you may prevent this by not adding +1 on newRI
if (numRounds >= rounds.Length)
{
newRI = new RoundInfo[numRounds]; //remove +1 here
//etc codes
}
I don't know what is your intention in this part
// creates a new array of RI objects if numRounds is greater than rounds.Length
copying an array but exceeds previous array length is impossible. It seems you're trying to do (newArray[oldArray.Length + 1] == oldArray[oldArray.Length]) which you cannot do because it will really go out of bounds.
newArray[11] can't have oldArray[11] because it is not existing
what you may try is the length of oldArray, not the new
for (int i = 0; i < rounds.Length; i++)
newRI[i] = rounds[i];
Upvotes: 1