为什么递增一个数组,递增另一个数组

Why does incrementing one array, increment another?

本文关键字:数组 另一个 一个 为什么      更新时间:2023-10-16

我在递增数组中的单个项时遇到问题。它最终增加了另一个数组。。它是怎么做到的?这就是我的

string simulateFIFO(darray<int> requests, int frameSize) {
string results;
int currentPages[frameSize];
int timer[frameSize];
int hits = 0;
int faults = 0;
cout << "STARTING FIFO" << endl;
for (int i = 0; i < requests.size(); i++) {
    cout << requests[i] << " ";
}
cout << endl;
cout << endl;
for (int i = 0; i < frameSize; i++) {
    currentPages[i] = -1;
    timer[i] = 0;
}
// Start Calculations
for (int i = 0; i < requests.size(); i++) {
    bool requestSet = false;
    for (int j = 0; j < frameSize; j++) {
        if (currentPages[j] < 0) {
            // Current frame does not have a page
            cout << "FRAME IS EMPTY" << endl;
            currentPages[j] = requests[i];
            requestSet = true;
            faults++;
            j = frameSize;
        }
        else if (currentPages[j] == requests[i]) {
            cout << "FRAME IS SAME AS REQUEST" << endl;
            // Current Frame is set the the page being requested
            timer[j] = 0;
            requestSet = true;
            hits++;
            j = frameSize;
        }
        cout << currentPages[j] << endl;
        timer[j]++;
        cout << currentPages[j] << endl;
    }
    // Check to see if a request was set or not
    if (requestSet == false) {
        cout << "FRAME NEEDS REPLACED" << endl;
        // The request wasnt set. Determine which frame to replace with the new request
        int lastUsed = 0;
        int lastUsedIndex = 0;
        for (int j = 0; j < frameSize; j++) {
            if (timer[j] > lastUsed) {
                lastUsed = timer[j];
                lastUsedIndex = j;
            }
        }
        currentPages[lastUsedIndex] = requests[i];
        //timer[lastUsedIndex] = 0;
        faults++;
    }
    cout << "HEY 3: " << currentPages[0] << endl;
    cout << "NEW FRAME: ";
    for (int j = 0; j < frameSize; j++) {
        cout << currentPages[j] << " ";
    }
    cout << endl;
    cout << endl;
}
cout << "FIFO" << endl;
cout << faults << endl;
cout << hits << endl;
cout << endl;
return results;

}

我的输出最终成为

01.

为什么增加一个数组实际上也会增加另一个数组?

您的代码包括一个可能的执行路径:

j = frameSize;

然后是

timer[j]++;

这访问越界:对于维度为frameSize的数组,有效索引为0frameSize-1

我猜你实际上是想退出循环;如果是,则用CCD_ 5替换CCD_ 4。

注:。ISO C++中不允许使用int timer[frameSize];;数组边界必须在编译时已知。您的代码依赖于编译器扩展。