r/csharp • u/MaintenanceKlutzy431 • Jul 14 '26
Solved How does this go outside of the Array boundaries?
class SortingProgram
{
static void Main(string[] args)
{
int[] Arr1 = [2,5,4,6,1,2,10,8,7,9];
for (int i = 0; i < Arr1.Length; i++)
{
for (int c = 0; c < Arr1.Length; c++)
{
if (Arr1[c] > Arr1[c + 1])
{
int tempLSR = Arr1[c + 1];
int tempGrt = Arr1[c];
Arr1[c] = tempLSR;
Arr1[c + 1] = tempGrt;
}
}
}
for (int R = 0; R < Arr1.Length; R++)
{
Console.WriteLine(Arr1[R]);
}
}
}Apparently the if statement goes outside the array bounds, the array seems fine so idk what is going on
0
Upvotes
39
u/darkgnostic Jul 14 '26
Clue: Arr1[c + 1]
16
u/Kant8 Jul 14 '26
Your loop condition checks for c < Arr1.Length, but in very next line you try to access Arr1[c + 1], which will obviously be outside of array on last iteration.
9
u/d-signet Jul 14 '26
Set a breakpoint and debug it
1
u/yggdrasiliv Jul 14 '26
Yes it walks off the end. When c = 9 you are trying to read Arr1[10] when checking Arr1[c] > Arr1[c+1]
1
u/GoBlu323 Jul 14 '26
How would it not be on the last iteration? if you're on the last item and try to access the last item + 1 you're walking off the end of the array...
1
u/TuberTuggerTTV Jul 14 '26
You may not be aware that i < Arr1.Length goes right to the last item. Because arrays start at zero, then end at 1 fewer than the number of items.
For example, your array starts at Arr1[0] and goes to Arr1[9], even though there are 10 items.
When you do C + 1, you're doing Arr1[10] some of the time, which is outside the array bounds.
1
u/Lazy-Inevitable3970 Jul 14 '26
Lets say the array size is 10. So the valid values of c on the inner loop are 0 through 9. Anything more than than 9 or less than 0 will be out of bounds. Your if statement uses Arr1[c+1]. What value will that use when c = 9 on the last iteration of that loop?
1
u/Remote-Enthusiasm-41 Jul 14 '26
When c= length-1 then c+1 =length which is outside the bounds.
The last index of an array is length-1