2014-11-16 2 views
-3

Я создал эту программу для назначения. Компилятор выполняет это, но когда я бегу, чтобы проверить выход, он дает следующее сообщение об ошибке:

enter image description here

код приведен ниже:Я создал эту программу, но ее выдача «ошибка сегментации (ядро сбрасывала)», что мне делать?

#include <iostream> 
 
using namespace std; 
 

 
class Node { 
 
    private: 
 
     int testscore; 
 
     int intmarks; 
 
     char * name; 
 
     Node * nextnode; 
 
    public: 
 
     void settestscore (int testscore) { this -> testscore = testscore; } 
 
     int gettestscore() { return testscore; } 
 
     void setintmarks (int intmarks) { this -> intmarks = intmarks; } 
 
     int getintmarks() { return intmarks; } 
 
     void setname (char * name) { this -> name = name; } 
 
     char * getname() { return name; } 
 
     void setnext (Node * nextnode) { this -> nextnode = nextnode; } 
 
     Node * getnext() { return nextnode; } 
 
}; 
 

 
class List { 
 
    private: 
 
     int size; 
 
     Node * headnode; 
 
     Node * currentnode; 
 
     Node * lastcurrentnode; 
 
    public: 
 
     friend void printlist(List list); 
 
     friend List addcandidates(); 
 
     List() { 
 
      headnode = new Node(); 
 
      currentnode -> setnext(NULL); 
 
      currentnode = NULL; 
 
      lastcurrentnode = NULL; 
 
      size = 0; 
 
     } 
 
     void addnode(int score, int marks, char * name) { 
 
      Node * newnode = new Node(); 
 
      newnode -> settestscore (score); 
 
      newnode -> setintmarks (marks); 
 
      newnode -> setname (name); 
 
      if (currentnode != NULL) { 
 
       newnode -> setnext (currentnode -> getnext()); 
 
       currentnode -> setnext (newnode); 
 
       lastcurrentnode = currentnode; 
 
       currentnode = newnode; 
 
      } 
 
      else { 
 
       newnode -> setnext (NULL); 
 
       currentnode -> setnext (newnode); 
 
       lastcurrentnode = headnode; 
 
       currentnode = newnode; 
 
      } 
 
     } 
 
     int gettestscore() { 
 
      if (currentnode != NULL) 
 
       return currentnode->gettestscore(); 
 
     } 
 
     int getintmarks() { 
 
      if (currentnode != NULL) 
 
       return currentnode->getintmarks(); 
 
     } 
 
     char * getname() { 
 
      if (currentnode != NULL) 
 
       return currentnode->getname(); 
 
     } 
 
     bool next() { 
 
      if (currentnode == NULL) { 
 
       return false; 
 
      } 
 
      lastcurrentnode = currentnode; 
 
      currentnode = currentnode -> getnext(); 
 
      if (currentnode == NULL || size == 0) { 
 
       return false; 
 
      } 
 
      else 
 
       return true; 
 
     } 
 

 
}; 
 

 
List addcandidates() { 
 
    List list; 
 
    list.addnode(50, 20, "Annie Khalid"); 
 
    list.addnode(35, 30, "Humaira Arshad"); 
 
    list.addnode(37, 29, "Atif Aslam"); 
 
    list.addnode(59, 10, "Qurat-ul-Ain Baloch"); 
 
    list.addnode(25, 9, "Sanam Marvi"); 
 
    list.addnode(44, 11, "Ali Zafar"); 
 
    list.addnode(59, 16, "Farhan Saeed"); 
 
    list.addnode(50, 22, "Amanat Ali"); 
 
    list.addnode(60, 28, "Junaid Jamshed"); 
 
    list.addnode(78, 17, "Shahzad Roy"); 
 
    list.addnode(78, 15, "Ali Azmat"); 
 
    list.addnode(40, 30, "Nadeem Abbas"); 
 
    return list; 
 
} 
 

 
void printlist(List list) { 
 
    Node * tempnode = list.currentnode; 
 
    list.currentnode = list.headnode; 
 
    for (int i = 1; list.next(); i++) { 
 
    cout << i << ": " << list.getname() << "\t \t" << list.gettestscore() << "\t \t" << list.getintmarks() ; 
 
    } 
 
    list.currentnode = tempnode; 
 
} 
 

 
main() { 
 
    List list = addcandidates(); 
 
    printlist(list); 
 
}
Я не мог найти, где проблема является? Мне нужна помощь. Спасибо заранее.

+3

Я бы бежал к холмам с мокрым фланелем над моим лицом - или использовал отладчик, чтобы сузить его –

+2

_ «Что мне делать» _ Скорее всего, разыгрывание какого-то свисающего или неправильно инициализированного указатель. Используйте отладчик и пройдите через свой код, чтобы узнать подробности. –

+0

@EdHeal У вас все еще есть близкие голоса сегодня? Дайте им один ... –

ответ

1

ошибка лежит в вашем конструкторе List:

List() { 
    headnode = new Node(); 
    currentnode->setnext(NULL); // <--- error is here! 
    currentnode = NULL; 
    lastcurrentnode = NULL; 
    size = 0; 
} 

На данный момент указатель currentnode является NULL (и вы настраиваете его NULL потом также, что не имеет смысла). Сначала вам нужно создать новый Node и назначить его currentnode, чтобы он работал, как и вы с headnode, или назначил headnode на currentnode напрямую (как вам кажется, вы используете currentnode для итерации, что бы установить вещи " правильно "во время строительства).

Когда вы являетесь разыменованием (вызывая setnext()), ваш currentNode, пока он NULL, ваша программа вылетает.

В коде есть много других вещей, вы должны действительно пересмотреть его и вникать в несколько учебников по семантике-указателю. Но, отвечая на ваш вопрос, обозначенная строка - это ваша проблема.

Кроме того, работает это с помощью отладчика и шагать через ваш код очень прост и позволяет вам найти такого рода ошибки с легкостью :)

EDIT, так же, как Heads-Up: Даже если вы решить эту проблему , вы не собираетесь печатать список. Ваше управление currentnode и headnode неверно, поэтому вы получите неверный список ссылок, и после исправления этого, ваша печать также не работает. Извините, что разорвал новости ...

+0

хм ... собираюсь написать его снова, покажет окончательный вывод. – arximughal

Смежные вопросы