当我打印2D数组“需要”的值时,我得到两个不同的结果。在初始化循环中,我打印出所有数组元素,如下面的输出部分所示。需要[0] [0]时,输出为7(输出部分的右上角,“需要[i] [j]:00 7”)。
然后在循环之外,我尝试直接调用这个元素,但这次需要[0] [0]返回0。
这是针对Banker的算法分配,其中资源在文本文件中指定,然后由我的程序解析。我认为这是唯一相关的代码部分。我确定这是一些指针问题,但我从来没有接受过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 :(得分:1)
need[i] = new int[numResources];
应该在for (int j...
您可以通过不使用手动内存管理来避免这种情况,例如:
std::vector< std::vector<int> > need(numProc, numResources);
答案 1 :(得分:0)
我没有仔细阅读,但我看到了你的分配
need[i] = new int[numResources];
它运行numResources * numProc次。
答案 2 :(得分: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];
对于每个单元格需要[i],前一行执行numResources次。 Profligate内存泄漏。 此外,它为您提供归零内存,所以当然它打印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;
max
和allocation
在哪里定义?
}
}
cout << "need[0][0]" << need[0][0] << endl;