Warm tip: This article is reproduced from serverfault.com, please click
c#

This piece of code gives me an error, and I can't figure out why?

发布于 2021-10-20 20:40:23

I am trying to find the biggest number in that struct array with this code:

max=0;
for (i = 1; i <= team.Length; i++)
{
    if (team[i].Point > team[max].Point) 
    { 
        max = i; 
    }

It gives me an error that it System.OutOfRangeException. Please help.

Questioner
Csetox
Viewed
0
JoelFan 2021-10-21 04:45:51

Arrays in C# are 0-based, not 1-based. Change your for loop:

for (i = 1; i < team.Length; i++)

NOTE: Edited based on feedback by @juharr