2014-10-27 143 views
0

我是一名編程愛好者,並且遇到一個錯誤,表示「運行時檢查失敗#2 - 變量'store'周圍的堆棧已損壞。」我之前查找過這個錯誤,但我沒有看到適用於我正在嘗試做的任何修復。看起來這個錯誤可能因各種原因而發生。調試錯誤堆棧變量損壞

我的代碼完全符合我的要求,但我不明白爲什麼會出現此錯誤,如果有人能向我解釋這一點,我將非常感激。謝謝!

#include <iostream> 
using namespace std; 

int main() 
{ 
    int store[4] = {}; 

    for (int i = 0; i != 5; i++) 
    { 

     cout << "Enter the sales of store " << (i + 1) << ": "; 
     cin >> store[i]; 
    } 

    cout << "\nSALES BAR GRAPH\n(Each * represents $100)\n"; 

    for (int i = 0; i != 5; i++) 
    { 
     int a = (store[i]/100); 
     cout << "\nStore " << (i + 1) << ": "; 
     for (int i = 0; i < a; i++) 
     { 
      cout << "*"; 
     } 
    } 

    cout << "\n"; 

    system("pause"); 
} 

回答

1

for循環是不正確的:

for (int i = 0; i != 5; i++) 

此引用store[4],這是出界,如果你宣佈int store [4]。如果要將商店尺寸保持爲4,則應將環路更改爲:

for (int i = 0; i < 4; i++)