1

我刚刚开始学习 c++,这是我用结构完成的第一段代码,但是当我运行它时,我遇到了分段错误。我正在用 g++ 在 linux 中编译它。任何人都可以看到错误在哪里,我知道是什么导致了分段错误,但我看不出是什么导致了它。

所有帮助表示赞赏。

#include <iostream>
using namespace std;

struct people
{
string forename;
string lastname;
int age;
};

int main()
{
int num_numbers; //ask the user how many numbers the sequence will contain
cout << "Enter how people will be entered : \n";
cin >> num_numbers; // stores the user input

people peoples[num_numbers];

for(int x = 0; x < num_numbers; x++) 
{
   cout<<"Enter forename "<< x <<":\n";
   cin >> peoples[x].forename;
   cout<<"Enter surname "<< x <<":\n";
   cin >> peoples[x].lastname;
   cout<<"Enter age "<< x <<":\n";
   cin >> peoples[x].age;
}

for(int i = 0; i<= num_numbers; i++)
{
    cout << peoples[i].forename;

    cout << peoples[i].lastname;

    cout << peoples[i].age;
}

//delete[] peoples;
}
4

1 回答 1

2

首先,这个:

people peoples[num_numbers];

是非标准扩展。其次,这里:

for(int i = 0; i<= num_numbers; i++)
//             ^^^^^^^^^^^^^^^

您将超出范围,因为具有大小的数组具有num_numbers0to的索引num_numbers - 1

于 2013-10-19T14:44:25.197 回答