Search code examples
c#indexingbounds

C# 'Index was outside the bounds of the array.' for one array but not another


I have 2 arrays for storing 2 series of inputs from the user. I set the bounds for both arrays to be equal to the same variable, but when inputting the info, after the final input on the first array, i get an exception 'Index was outside the bounds of the array.'.

When i tried to change the bounds of the arrays to constant numbers, they were behaving normally.

            string[] names = new string[movies-1];
            double[] ratings = new double[movies-1];
            for(int i = 0; i < movies; i++)
            {
                names[i] = Console.ReadLine();
                ratings[i] = Convert.ToDouble(Console.ReadLine());
            }

System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'


Solution

  • You're just off by one (twice) -

    1. The arrays should be instantiated to be in the length of movies, not movies-1

    2. When iterating, you want i to be equal to movies-1 at most, because the array assignments start at 0.

    Think about it - if movies is equal to 1 (one movie), you're currently instantiating an array with 0 slots - any index you try to access will be out of bounds.