2015-11-18 42 views
-2

我在增加數組中的單個項目時遇到問題。它最終增加了另一個數組..它是如何做到的?這就是我:爲什麼遞增一個數組,遞增?

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 

爲什麼增加一個陣列實際上增加了其他的呢?

謝謝。

+5

請發佈[MCVE](http://stackoverflow.com/help/mcve)。 –

+1

通過以某種方式修改代碼來編譯代碼,我無法重現該問題。正如Anon Mail建議的那樣,請發佈[mcve]。 –

+4

int currentPages [frameSize];在ISO C++中是非法的。如果編譯完成,那麼你依賴於一個編譯器擴展,它可以做任何事情。但是在'...'中你可能會忽略一些未定義行爲的調用,例如'j'被改爲超出循環邊界 –

回答

1

代碼包括執行的可能的路徑:

j = frameSize; 

隨後

timer[j]++; 

此訪問超出範圍:對於尺寸frameSize的陣列,該有效索引是0通過frameSize-1

我想你實際上是想退出循環;如果是這樣,則用break;替換j = frameSize;

注意:在ISO C++中不允許使用int timer[frameSize];;在編譯時必須知道數組邊界。您的代碼依賴於編譯器擴展。