當我打印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
您正在每個單元格上重新創建錶行,並移動'need [i] = new int [numResources];'它應該在'for(int i = 0; i
nmikhailov