Search code examples
c#compiler-errorsunassigned-variable

how to get rid of compiler error: C# use of unassigned local variable?


I have some questions why C# doesn't like the coordinates[j] part and what I can do about it.

string[] lines = System.IO.File.ReadAllLines(@"C:\Users\sp\Dropbox\ProjectEuler\102\p102_triangles.txt");
string[] coordinates_str;
double[] coordinates; //Contains the coordinates for each line A1(x,y), A2(x,y), A3(x,y)
long ln = lines.Length;
Console.WriteLine("Length: " + ln.ToString());
for (int i = 0; i < ln; i++)
{
    Console.Write(i);
    Console.Write(lines[i]);
    coordinates_str = lines[i].Split(',');
    for (int j = 0; j < 6; j++)
    {
        coordinates[j] = Convert.ToDouble(coordinates_str[j]);
    }
}

Solution

  • You assign values to elements of coordinates without actually allocating storage first

    double[] coordinates = new double[6];
    

    So far you have just said coordinates is a reference to an array of doubles, but you have not said how large that array is (you have not allocated any storage).