سؤال

I"m trying to understand link list but every example I've tried to copy gives me a segmentation fault. This is my example program that I am working on.

in contacts.h

struct people{
  string last;
  string first;
  int age;
  people *next;
};

class Contacts {
 private:
  people *head;
 public:
  Contacts() {
   head=NULL;
  };
  void add(string, string, int);
  void display();
};

in main.cpp

//menu items
//cin >> option
//if option == 1, addContact
//if option == 8, displayContact
//basic in and out here no need to show code

in main.h

void addContact() {

  Contacts *ptr;     

  int i, loop=0, a=0;
  string l, f;

  cout << "number of contacts " << endl;
  cin >> loop;

  for(i=0; i<loop; i++) {

    cout << "enter last name ";
    cin >> l;

    cout << "enter first name ";
    cin >> f;

    cout << "enter age ";
    cin >> a;

  }

  ptr->add(l,f,a);

}
void display() {

 Contacts *ptr;
 ptr->display();
}    

in contacts.cpp

void Contacts::add(string l, string f, int a) {

  people *node = new people;

  node->last=l;
  node->first=f;
  node->age=a;

  node->next=NULL;
}

void Contacts::display() {
 people *tmp = head;
 while(tmp!=NULL) {
   cout << tmp->last << endl;
   cout << tmp->first << endl;
   cout << tmp->age << endl;
   tmp->next;
 }

the add function works then display() gives me a segfault

هل كانت مفيدة؟

المحلول

Member function add should be defined the following way

void Contacts::add( const string &l, const string &f, int a ) 
{
    head = new people { l, f, a, head };
}

Or if your compiler does not support initializer lists with the new operator then

void Contacts::add( const string &l, const string &f, int a ) 
{
    people *p = new people;

    p->last = l;
    p->first = f;
    p->age = a;
    p->next = head;

    head = p;
}

Member fuunction display should be declared as

void Contacts::display() const;

and defined as

void Contacts::display() const
{
    for ( people *tmp = head; tmp; tmp = tmp->next )
    {
        cout << tmp->last << endl;
        cout << tmp->first << endl;
        cout << tmp->age << endl;
        cout << endl;
    }
}

The other two functions should be defined the following way

void addContact( Contacts &contacts ) 
{
    int n = 0;

    cout << "number of contacts " << endl;
    cin >> n;

    for ( int i = 0; i < n; i++ ) 
    {
        string l, f;
        int a = 0;

        cout << "enter last name ";
        cin >> l;

        cout << "enter first name ";
        cin >> f;

        cout << "enter age ";
        cin >> a;

        contacts.add( l, f, a );
    }
}


void display( const Contacts &contacts ) 
{
    contacts.display();
}    

And in main you should define an object of type

Contacts contacts;

and use it as the argument of the functions above.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top