2016-11-16 119 views
0

我想将值赋给2D整数数组的第0个位置。但是,我得到一个NullReferenceException异常,虽然我传递了适当的值。赋值给2d数组给我例外

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 
    } 
} 
+0

您的Ctable为空,这是您的问题,请检查我发布的问题。了解什么是调试 – mybirthname

回答

4

您不能正确初始化2D阵列Ctable,它仍然为空。看我下面的例子。我使用方法void GetTable(int m, int n)的输入参数mn的大小初始化阵列。

您的循环也不正确。数组是零索引(0,n - 1)。你会发现一些额外的信息来初始化阵列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; 
    } 
} 

但是,您将始终覆盖Ctable。可能您正在寻找类似的东西:

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; 
    } 
} 
+0

您也可以显示索引n的用法和数据填充,这里只填充索引m。大多数OP不太了解。 –