c++ - for 循环在第一次迭代后崩溃

标签 c++ for-loop crash structure

#include <iostream>
#include <string>

using namespace std;

struct person
{
    string name;
    int numberofpies;
    string flavour;
};

int main ()
{
    for (int i=1; i<10; i++)
    {
    cout << "press <1> to add a person or press <2> to get results" << endl;
    int input;
    cin >> input;
    person newperson[i];
    string names, flavours;
    int numbersofpies;
    if (input==1)
      {
        cout << "please enter your name " << endl;
        cin >> names;
        cout << "enter the number of pies you ate" << endl;
        cin >> numbersofpies;
        cout << "enter the flavour" << endl;
        cin >> flavours;
        newperson[i].numberofpies=numbersofpies;
        newperson[i].flavour=flavours;
        newperson[i].name=names;
      }
      else if(input == 2)
      {
          int x=1;
          while (x>i)
          {
              cout << "name : " << newperson[x].name << endl;
              cout << "number of pies : " << newperson[x].numberofpies<< endl;
              cout << "flavour: " << newperson[x].flavour << endl;

          }goto point;
      }


    }point:
        return 0;    
}

我的问题是,这段代码正常编译并完美运行,直到第一个循环结束,然后崩溃,因此在尝试和尝试不同的解决方案后,我意识到问题出在“if 语句”的最后三行

newperson[i].numberofpies=numbersofpies;
newperson[i].flavour=flavours;
newperson[i].name=names;

因为删除它们后问题就消失了。然而,该程序显然不会做它应该做的事情,所以我想我的问题是这些行出了什么问题,如果它们不是问题是什么?我该如何解决它? 另外,如果它有我可以学习的想法,我根本不介意其他方法,但我最重要的是有兴趣了解问题以学习不让程序运行?

最佳答案

person newperson[i]; 正在声明一个可变长度数组,VLA 是一个非标准的特定于供应商的编译器扩展。不要使用它们。如果您需要可变长度数组,请使用 std::vector 代替。

在这种情况下,您的代码具有未定义的行为,因为您的循环变量i始终超出您正在分配的VLA的范围,因此当您尝试设置作为数组的成员,newperson[i] 正在访问数组外部的周围内存。这就是您的代码崩溃的原因。

数组索引是从 0 开始的,但循环变量是从 1 开始的。因此,在第一次迭代中,您分配一个包含 1 个元素的数组,但随后访问第二个元素。在第二次迭代中,您分配一个包含 2 个元素的数组,但随后访问第三个元素。等等

关于c++ - for 循环在第一次迭代后崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38679129/

相关文章:

c++ - SSE 添加比 + 运算符慢

magento - nginx recv() 失败 (104 : Connection reset by peer) while reading response header from upstream

android - 如果用户在年龄编辑文本中输入字母,如何指示错误? (安卓工作室)

swift - 尝试将事件标签用作标题时发生崩溃

c++ - 在 C++ 中动态改变数组大小

c++ - 为什么 operator new 函数需要转换

c++ - 需要关于 boost::mpl 的解释

arrays - 如何从两个元素列表中获取一个元组

python - Flask - jinja 模板 forloop 增加循环索引

java - 如何在数组中添加 40 以下的数字