-1

I am trying to assign values to 0th position of a 2D integer array. However, I get a NullReferenceException exception, though I am passing proper values.

public static int[,] Ctable;

private static void GetTable(int m,int n)
{
    m = 16;
    for (int i = 1; i <= m; i++)
    {
        Ctable[i, 0] = 1; // Here it is giving Exception
    }
}
Roshni Gandhi
  • 336
  • 4
  • 13

1 Answers1

4

You don't initialize the 2D array Ctable correctly, it's still null. See my example below. I initialize the array with the size of the input parameter m and n of the method void GetTable(int m, int n).

Your loop is not correct as well. Arrays are zero indexed (0, n - 1). You will find some additional information to initialize arrays here.

public static int[,] Ctable;

private static void GetTable(int m, int n)
{
    Ctable = new int[m, n]; // Initialize array here.

    for (int i = 0; i < m; i++) // Iterate i < m not i <= m.
    {
        Ctable[i, 0] = 1;
    }
}

However, you will always overwrite Ctable. Probably you're looking for something like:

private const int M = 16; // Size of the array element at 0.

private const int N = 3; // Size of the array element at 1.

public static int[,] Ctable = new int [M, N]; // Initialize array with the size of 16 x 3.

private static void GetTable()
{
    for (int i = 0; i < M; i++)
    {
        Ctable[i, 0] = 1;
    }
}
Andre Hofmeister
  • 3,185
  • 11
  • 51
  • 74