【问题标题】:Run-Time Check Failure #2 Error for All My Variables我的所有变量的运行时检查失败 #2 错误
【发布时间】:2016-02-02 04:17:49
【问题描述】:

我的程序运行良好,但在我选择退出后,它给了我 “运行时检查失败 #2 - 变量 'col' 周围的堆栈已损坏。”我的所有变量。

我只想知道如何解决正在发生的事情。

我的主要:

    int main()
{
    int row, col;
    double revenue = 0;
    char choice;
    char seats[MAX_ROWS][MAX_COLS];
    int tickets_sold = 0;

    double prices[MAX_ROWS] = { 40, 40, 35, 35, 35, 30, 30, 25, 25, 25, 12.5, 12.5, 12.5, 9.5, 9.5 };

    for (int rows = 0; rows < MAX_COLS; rows++)
    {
        for (int cols = 0; cols < MAX_COLS; cols++)
        {
            seats[rows][cols] = '*';
        }
    }

    do
    {
        menu();
        cin >> choice;

        if (choice == '1')
            display(seats, tickets_sold, revenue);

        else if (choice == '2')
        {
            do
            {
                cout << "\nEnter row number: " << endl;
                cin >> row;
                cin.clear();
                cin.ignore();

                cout << "Enter column number: " << endl;
                cin >> col;
                cin.clear();
                cin.ignore();

                if (row < MIN_ROWS || row > MAX_ROWS || col < MIN_COLS || col > MAX_COLS)
                    cout << "\nRow number must be between 0 and 14 and Column number must be between 0 and 19." << endl;
                else if (seats[row][col] != '*')
                    cout << "\nSeat is currently unavailable." << endl;
            } while (row < MIN_ROWS || row > MAX_ROWS || col < MIN_COLS || col > MAX_COLS || seats[row][col] != '*');

            seats[row][col] = '#';
            revenue += prices[row];

            tickets_sold++;
        }

        else if (choice == 'q')
            cout << "\nQuiting the program..." << endl;

        else
            cout << "\nInvalid selection." << endl;
    } while (choice != 'q');


    system("PAUSE");
    return 0;
}

【问题讨论】:

  • 您有没有预定过边缘的一个座位(row=MAX_ROWS 或 col=MAX_COLS)?
  • 这是错误的:if (row &lt; MIN_ROWS || row &gt; MAX_ROWS || col &lt; MIN_COLS || col &gt; MAX_COLS) 它应该是 if (row &lt; MIN_ROWS || row =&gt; MAX_ROWS || col &lt; MIN_COLS || col =&gt; MAX_COLS),因为您分配了 char seats[MAX_ROWS][MAX_COLS]; 并且 c++ 使用基于 0 的索引意味着席位[MAX_ROWS][MAX_COLS] 超出范围。
  • 我尝试将其更改为 >= 和
  • 你的 while() 有同样的问题 while (row &lt; MIN_ROWS || row &gt; MAX_ROWS || col &lt; MIN_COLS || col &gt; MAX_COLS || seats[row][col] != '*')
  • 谢谢,它没有解决我想要的问题,但它解决了我不知道的问题!

标签: c++ c visual-studio


【解决方案1】:

这只是“堆栈溢出”问题。您写入了一些超出局部变量范围的数据。 大多数情况下,您应该首先检查您对本地数组的操作。

这样的话,你的数组初始化有问题:

for (int rows = 0; rows < MAX_COLS; rows++)
{
    for (int cols = 0; cols < MAX_COLS; cols++)
    {
        seats[rows][cols] = '*';
    }
}

行和列由相同的宏 MAX_COLS 初始化。显然 MAX_COLS 大于 MAX_ROWS。

【讨论】:

  • 谢谢!这解决了问题!我不敢相信我没有看到——这对我来说是一个可怕的检查错误。
猜你喜欢
  • 2021-04-03
  • 1970-01-01
  • 2013-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多