2016-11-16 122 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不太瞭解。 –