0

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?

  • 3
    `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 people(n);` – PaulMcKenzie Feb 12 '22 at 16:25
  • Oops! Didn't realize I was trying to access people[n] instead of people[i]. My bad. –  Feb 12 '22 at 16:25
  • 1
    you are indexing people with wrong variable at cin>>people[n].name; – whatishappened Feb 12 '22 at 16:25
  • 1
    @Gabriel If you had used vector, then `cin >> people.at(n).name;` would have pinpointed the issue, and issued a `std::out_of_range` exception instead of a core dump. – PaulMcKenzie Feb 12 '22 at 16:26

0 Answers0