当我打印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