- Home /
Weird - IndexOutOfRangeException: Array index is out of range.
Here's my code
int i = 0;
int intTmp_Ori = 0; //For storing the result value (100,200,300)
int intTmp = 0; //For storing the result value (1,2,3)
bool bNextMove = false;
int nArray1 = 0; //record
int nArray2 = 0; //Column
intTmp_Ori = (int)(arrPart[0]);
intTmp = (int)(intTmp_Ori / 100);
for (i = 0; i < arrPart.Length; i++) //Turns history
{
if (i == 0) //If it's your first history
{
intTmp_Ori = (int)(arrPart[i]); //Save current value
intTmp = (int)(intTmp_Ori / 100); //P,B,T Value
bNextMove = false;
}
else //From the second
{
if ((int)((int)(arrPart[i]) / 100) == 3) //Tie
{
bNextMove = false;
}
else if ((int)((int)(arrPart[i]) / 100) != intTmp && intTmp != 3)//Unlike previous result
{
nArray1++; //Go to next record
//reset
nArray2 = 0;
intTmp_Ori = (int)(arrPart[i]);
intTmp = (int)(intTmp_Ori / 100);
bNextMove = false;
}
else if ((int)((int)(arrPart[i]) / 100) == intTmp || intTmp == 3)//If it is the same as the previous result.
{
if (intTmp == 3) nArray2--;
bNextMove = true;
intTmp_Ori = (int)(arrPart[i]);
intTmp = (int)(intTmp_Ori / 100);
}
}
if (bNextMove) nArray2++;
arrayBigEyeRoad[nArray2,nArray1] = intTmp;
}
This code right here arrayBigEyeRoad[nArray2,nArray1] = intTmp;
is giving me the IndexOutOfRangeException
Here is my declaration of 2D Array int[,] arrayBigEyeRoad = new int[6, 104];
I tried also like this int[,] arrayBigEyeRoad = new int[104, 6];
but no luck
Do you understand what the Index out of range means? nArray2 or nArray1 (or both) are either negative or nArray2 is >= 6 or nArray1 >= 104.
Yeah I understand that clearly but why is it giving me an Index out of range on the 6,5 after that it pops out
So nArray2 = 6 and nArray1 = 5? If so, then 6 is outside of the array. Index in the array starts from 0, not from 1. So, the 6th elements index is 5. Since, the size in that dimension is 6, the element with an index 5 is the last one. An element with an index 6 doesn't not exist, therefore the index is outside of range.
Answer by Summit_Peak · Jun 01, 2018 at 12:31 PM
You might check if nArray2 < 0. A negative index will also throw an IndexOutOfRangeException.
Try changing:
if (intTmp == 3) nArray2--;
to
if (intTmp == 3 && nArray2 > 0) nArray2--;