2014-10-27 140 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++)