Blinx
Blinx

Reputation: 33

2D Matrix index out of bounds

I'm trying to create a 2D matrix which will be displayed and sorted in a table.

I'm having issues filling my matrix/array with numbers. I don't want duplicates in there and so a temporary List was created.

I've tried different things to fix the index out of bounds exception I get when add num to the list, but I don't know what is going.

I originally had all variables as static and not needed in the method. Then I tried putting them in the method to see what would happen if the variable wasn't static.

How would I go about fixing this error? (All done in a Console App)

    static int max;

    static int max_row;

    static int max_col;

    //static int[,] matrixArray = new int[max_row, max_col];

    //static List<int> list = new List<int>();

    //Filling the matrix
    public static void matrixFill(int[,] matrixArray, List<int> list)
    {
        for (int x = 0; x < max_row; x++)
        {
            for (int y = 0; y < max_col; y++)
            {
                Random rand = new Random();

                int num = rand.Next(10, 100);

                if (!list.Contains(num))
                {
                    matrixArray[x, y] = num;

                    //Index error occurs here
                    list.Add(num);
                }
                else
                {
                    y--;
                }
            }
        }
    }

        //What is happening in the main method until the error
        int[,] matrixArray = new int[max_row, max_col];

        List<int> list = new List<int>();

        Console.Write("Please enter matrix size: ");

        Int32.TryParse(Console.ReadLine(), out max);

        max_row = max;
        max_col = max;

        Console.WriteLine();

        matrixFill(matrixArray, list);

Upvotes: 0

Views: 82

Answers (1)

N.D.C.
N.D.C.

Reputation: 1601

The issue is that you define the size of matrixArray before the max_row and max_col parameters are set.

    List<int> list = new List<int>();

    Console.Write("Please enter matrix size: ");

    Int32.TryParse(Console.ReadLine(), out max);

    max_row = max;
    max_col = max;
    int[,] matrixArray = new int[max_row, max_col]; // move this here

Instead, move that definition to be after you ask the user for the max size, as above, so that the matrix you create is the same size as what you're expecting.

Upvotes: 1

Related Questions