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

Why does incrementing one array, increment another?

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

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;

}

我的输出结果是

0
1

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

您的代码包含可能的执行路径:

j = frameSize;

接着是

timer[j]++;

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

我猜你真的想退出循环;如果是这样,则将 j = frameSize; 替换为 break; .

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