Search code examples
c#multidimensional-arrayindexoutofrangeexception

First index of an array returns an IndexOutOfRangeException


I'm writing a Unity Script that reads a CSV file (2D and all numeric), breaks it down into floats that are appended to a 2D float array. Here is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LoadCalibration : MonoBehaviour
{
    public float[,] pc_array; // Reconstructed PC coefficient MD array (PCs as rows and variables as columns)

    // Start is called before the first frame update
    void Start()
    {
        // PC COEFFICIENTS

        pc_array = new float[20, 20];
        Debug.Log(pc_array);

        TextAsset pc_data = Resources.Load<TextAsset>("pc_coeff"); //Data is in as variables x PCs

        string[] variable = pc_data.text.Split(new char[] { '\n' }); // split pc_data into rows(each row is one variable, for all PCs)

        for (int i = 0; i < variable.Length - 1; i++)
        {
            string[] pc = variable[i].Split(new char[] { ',' }); // delegate each variable to a pc
            Debug.Log(i);

            for (int j = 0; j < pc.Length; i++)
            {
                Debug.Log(j);
                pc_array[j,i] = float.Parse(pc[j]); // Load float value into the pc_coeff MD array
            }

        }

    }
}

And it throws me this error:

IndexOutOfRangeException: Index was outside the bounds of the array.
LoadCalibration.Start () (at Assets/Scripts/LoadCalibration.cs:31)

Using Debug.Log() I have worked out that that the error occurs at i = 0 and j = 0 (the first index of the array), even though I declare it as a 20 x 20 array. I am new to C# so it may be very obvious what the error is but I can't work it out. Any help would be much appreciated!

I have used Debug.Log() to assess that the rest of the code is working (aka its reading the CSV file and converting each string entry into a single float point).


Solution

  •   for (int j = 0; j < pc.Length; i++)
    

    change to

      for (int j = 0; j < pc.Length; j++)