我刚刚开始学习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;
}
答案 0 :(得分:2)
首先,这个:
people peoples[num_numbers];
是非标准扩展名。其次,这里:
for(int i = 0; i<= num_numbers; i++)
// ^^^^^^^^^^^^^^^
你出界了,因为大小为num_numbers
的数组的索引从0
到num_numbers - 1
。