GTeofilov
GTeofilov

Reputation: 23

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.'

Upvotes: 1

Views: 17256

Answers (2)

Javier Silva Ort&#237;z
Javier Silva Ort&#237;z

Reputation: 2982

C# exhibits zero based indexing. That is, an array of size s will have its elements indexed from 0 to s - 1.

Since you declared the array names to be of size movies - 1, its elements are indexed from 0 to movies - 2. Therefore, the loop:

for(int i = 0; i < movies; i++)
{
    names[i] = Console.ReadLine();
    ratings[i] = ...
    ...

will try to access an out of bounds index in arrays names and ratings when i = movies - 1.

You should declare your arrays as:

string[] names = new string[movies];
double[] ratings = new double[movies];

so that they are consistent with your for loop definition.

Upvotes: 0

Nimrod Dolev
Nimrod Dolev

Reputation: 622

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.

Upvotes: 5

Related Questions