Question

I am just beginning to learn c++, and this is the first piece of code I have done with structs, but when I run it I get a segmentation fault. I am compiling it in linux with g++. Can anyone see where the error is, I understand what causes a segmentation fault but I cannot see what is causing it.

All help appreciated.

#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;
}
Was it helpful?

Solution

Firstly, this:

people peoples[num_numbers];

Is non-standard extension. Secondly, here:

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

You're going out of bounds, because array with size num_numbers has indexes from 0 to num_numbers - 1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top