【问题标题】:Why does Program fail after conclusion为什么程序结束后失败
【发布时间】:2014-02-17 03:45:37
【问题描述】:

我希望有人能回答这个问题并实际上教我一些东西。我有这个简单的小sn-p代码,它可以正常工作,但是在程序结束后Windows会抛出以下错误

program.exe 已停止工作 一个问题导致程序停止 正常工作。 Windows 将关闭程序并通知您,如果 解决方案可用。

带有关闭程序的按钮

下面的代码询问用户会有多少玩家,然后根据玩家数量创建一个大小等于玩家数量的数组。然后 for 循环将每个字符名称打印到屏幕上。这是代码

int main()
    {
        int numplay;
        cout<<"How many players will there be? ";
        cin>> numplay;
        cin.ignore();
        cin.get();
        string *players = new string[numplay - 1]; 
        for (int x = 1; x < numplay + 1; x++) {     
        string name;
        cout<<"What is Player "<< x <<"'s name? ";
        cin>> name;
        players[x - 1] = name;
        cin.ignore();
        }
        cin.clear();
        cin.sync();
        cin.get();
        for (int x = 0; x < numplay; x++) {
        cout<< players[x] <<"\n";
        }
        delete[] players;
    }

事情就像我说的代码编译并运行良好它只是在最后 Windows 抛出了上面提到的错误,几乎没有细节。如果从数组声明中删除 -1,问题就会得到缓解。但是,这会创建一个额外的未使用的数组元素。我希望这个问题是连贯的,它完全是出于好奇,因为 Windows 没有提供太多细节。

【问题讨论】:

    标签: c++ arrays visual-c++


    【解决方案1】:

    您正在越界访问数组。正如您所暗示的,从数组分配中删除 -1 使其工作。

    string *players = new string[numplay - 1];   // Wrong
    

    如果用户输入3,那么你将只分配一个包含2个元素的数组。该数字表示元素的数量,而不是最大索引。

    正确的代码是:

    string *players = new string[numplay];
    

    我还建议您对在数组上运行的任何循环使用从零开始的索引。看到上面一行之后的循环是令人困惑的。改为这样做:

    for (int x = 0; x < numplay; x++) {     
        cout << "What is Player "<< x+1 <<"'s name? ";
        cin >> players[x];
        cin.ignore();
    }
    

    【讨论】:

      【解决方案2】:

      你分配numplay - 1数组元素,例如元素0 ... numplay - 2

      string *players = new string[numplay - 1];
      

      但在循环中,您访问的元素从0numplay - 1 包含,这是数组之外的一个元素

      for (int x = 1; x < numplay + 1; x++) {
          ...
          players[x - 1] = name;
      }
      

      在最后一次迭代中,您拥有x = numplay。这样,您就可以访问位于数组边界之外的players[numplay - 1]

      这也是原因,为什么要这样做

      string *players = new string[numplay];
      

      修复您的问题。因为现在,数组元素从0变为numplay - 1,符合for循环中的访问。

      【讨论】:

        【解决方案3】:
        string *players = new string[numplay - 1]; 
        for (int x = 1; x < numplay + 1; x++) {     
          ...
          players[x - 1] = name;
        }
        ...
        for (int x = 0; x < numplay; x++) {
          cout<< players[x] <<"\n";
          ...
        }
        

        您正在修改和使用数组边界之外的元素。这会导致未定义的行为。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-09-29
          • 2019-11-23
          • 2021-04-03
          • 1970-01-01
          • 1970-01-01
          • 2010-12-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多