2014-04-01 104 views
-1

當我打印2D數組的值「需要」時,我得到兩個不同的結果。在初始化循環中,我打印出所有的數組元素,如下面的輸出部分所示。在需要[0] [0]時,輸出爲7(輸出部分的右上方,「需要[i] [j]:00 7」)。C++數組值打印不一致

然後循環外,我嘗試直接調用這個元素,但是這個時候就需要[0] [0]返回0

這是一個銀行家算法分配,這裏的資源在文本中指定文件,然後由我的程序解析。我認爲這是唯一相關的代碼部分。我確信這是一些指針問題,但我從未接受過C/C++編程的指導,而我只是單純地指出了這一點。

// Initialize the need matrix 
need = new int*[numProc]; 
for (int i = 0; i < numProc; i++){ 
    for (int j = 0; j < numResources; j++){ 
    need[i] = new int[numResources]; 
cout << " max[i][j]:" << max[i][j]; 
cout << " allocation[i][j]:" << allocation[i][j]; 

need[i][j] = max[i][j] - allocation[i][j]; 
cout << " need[i][j]:" << i << j << " " << need[i][j] << endl; 
    } 
} 
cout << "need[0][0]" << need[0][0] << endl; 

這是輸出:

max[i][j]:7 allocation[i][j]:0 need[i][j]:00 7 
    max[i][j]:5 allocation[i][j]:1 need[i][j]:01 4 
    max[i][j]:3 allocation[i][j]:0 need[i][j]:02 3 
    max[i][j]:3 allocation[i][j]:2 need[i][j]:10 1 
    max[i][j]:2 allocation[i][j]:0 need[i][j]:11 2 
    max[i][j]:2 allocation[i][j]:0 need[i][j]:12 2 
    max[i][j]:9 allocation[i][j]:3 need[i][j]:20 6 
    max[i][j]:0 allocation[i][j]:0 need[i][j]:21 0 
    max[i][j]:2 allocation[i][j]:2 need[i][j]:22 0 
    max[i][j]:2 allocation[i][j]:2 need[i][j]:30 0 
    max[i][j]:2 allocation[i][j]:1 need[i][j]:31 1 
    max[i][j]:2 allocation[i][j]:1 need[i][j]:32 1 
    max[i][j]:4 allocation[i][j]:0 need[i][j]:40 4 
    max[i][j]:3 allocation[i][j]:0 need[i][j]:41 3 
    max[i][j]:3 allocation[i][j]:2 need[i][j]:42 1 
need[0][0]0 
+0

您正在每個單元格上重新創建錶行,並移動'need [i] = new int [numResources];'它應該在'for(int i = 0; i nmikhailov

回答

1

need[i] = new int[numResources];前應for (int j...

您可以通過不使用手動內存管理避免了這一點,例如

std::vector< std::vector<int> > need(numProc, numResources); 
+0

嗯,那很容易:)謝謝! –

0

我沒有讀到仔細,但我看到你的配置

need[i] = new int[numResources]; 

運行numResources * NUMPROC倍。

0
// Initialize the need matrix 
need = new int*[numProc]; 
for (int i = 0; i < numProc; i++) { 
    for (int j = 0; j < numResources; j++) { 
    need[i] = new int[numResources]; 

上一行爲每個單元執行numResources次需要[i]。內存泄漏泄漏。 此外,它給你零記憶,所以當然它打印0。

cout << " max[i][j]:" << max[i][j]; 
    cout << " allocation[i][j]:" << allocation[i][j]; 

    need[i][j] = max[i][j] - allocation[i][j]; 
    cout << " need[i][j]:" << i << j << " " << need[i][j] << endl; 

maxallocation哪裏定義?

} 
} 
cout << "need[0][0]" << need[0][0] << endl;