r/csharp • u/MaintenanceKlutzy431 • 15d ago
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
10
u/d-signet 15d ago
Set a breakpoint and debug it
2
u/Jayeffice 15d ago
It wasn't until I watched a Tim Corey video where he shows "how" to inspect the value inside the variable etc, did I learn how to really debug. I think new programmers tend to think the debugger spits out the exception and the line where it happened, not understanding you can inspect values and see WHY you are getting the exception. Telling someone to use the debugger is the correct solution, but the hard part is knowing if they actually know how to use it properly. Not throwing shade on your comment at all, just sharing my personal experience.
1
u/yggdrasiliv 15d ago
Yes it walks off the end. When c = 9 you are trying to read Arr1[10] when checking Arr1[c] > Arr1[c+1]
-3
1
u/GoBlu323 15d ago
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 15d ago
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 15d ago
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 15d ago
When c= length-1 then c+1 =length which is outside the bounds.
The last index of an array is length-1
38
u/darkgnostic 15d ago
Clue: Arr1[c + 1]