I'm trying to assign a name to a person using structs. The first input is the number n of people, then I create an array of people of size n and then assign a name to each i-nth person:
#include <iostream>
#include <algorithm>
using namespace std;
struct person{
string name;
};
int main(){
int n;
cin>>n;
person people[n];
for(int i=0; i<n; i++){
cin>>people[n].name;
}
for(int i=0; i<n; i++){
cout<<people[i].name<<"\n";
}
}
So it was supposed to assign names to, for example, 3 people. But I'm getting the following error after assigning a name to the first person:
3
John
Segmentation fault (core dumped)
What am I doing wrong?
int n; cin>>n; person people[n];-- This is not valid C++. Arrays in C++ must have their size denoted by a compile-time expression, not a runtime value. Instead, this should be:std::vector<person> people(n);cin >> people.at(n).name;would have pinpointed the issue, and issued astd::out_of_rangeexception instead of a core dump.