为什么这个功能导致崩溃? (多重表)

时间:2015-10-02 20:02:57

标签: c++ linked-list crash

我正在制作我的第一个多列表,到目前为止它只不过是一场噩梦。现在,我允许用户自己放置x,y斑点(class_number,student_number)。我的节点如下所示:

    typedef struct node {
        int student_number;
        int class_number;
        struct node* classpointer;
        struct node* studentpointer;
    }* nodePtr;

初始化
List::List() {
    head = nullptr;
    currClass = nullptr;
    currStudent = nullptr;
}

要添加数据值并设置指针,我有两个函数。

void List::addNodeToClass() {
    nodePtr n = new node;
    n->classpointer = NULL;

    cout << "What class number would you like to add?" << endl;
        int x;
    cin >> x;
    n->class_number = x;

    if(head != NULL) {
        currClass = head;
        while (currClass->classpointer != NULL) {
            currClass = currClass->classpointer;
        }
        currClass->classpointer = n;
    }
    else {
        head = n;
    }
}

void List::addNodeToStudent() {
    nodePtr n = new node;
    n->studentpointer = NULL;

    cout << "What student number would you like to add?" << endl;
        int x;
    cin >> x;
    n->student_number = x;

    if(head != NULL) {
        currStudent = head;
        while (currStudent->studentpointer != NULL) {
            currStudent = currStudent->studentpointer;
        }
        currStudent->studentpointer = n;
    }
    else {
        head = n;
    }
}

我在menu()函数中对这两个函数进行函数调用,而在main()中我只调用menu()

int menu() {
    int input;
    List List;
    while (input != 3) {
        cout << " " << endl;
        cout << "Press '1' to input a node" << endl;
        cout << "Press '2' to view the list of nodes" << endl;
        cout << "Press '3' to exit" << endl;
        cout << " " << endl;
        cin >> input;
        if (input == 1) {
        List.addNodeToClass();
        List.addNodeToStudent();
        }
        else if (input == 2) {
        List.PrintList();
        }
        else if (input == 3) {
            return 0;
        }
        else {
        cout <<"That is an invalid key" << endl;
        }
    }
}

当我运行程序时,我能够输入类节点,然后当我进入学生节点时,在点击后输入程序崩溃。我知道有很多东西要看,但我不明白为什么会这样。如果有人能告诉我这里做错了什么我会非常感激。谢谢。

2 个答案:

答案 0 :(得分:1)

addNodeToClass函数从不设置node->studentpointer。因此,当您在addNodeToStudent中关注该指针时,您将取消引用垃圾。

答案 1 :(得分:0)

使用默认的node构造函数,您的代码会更安全:

typedef struct node {
    node()
    {
        student_number = 0;
        class_number = 0;
        classpointer = nullptr;
        studentpointer = nullptr;
    }
    int student_number;
    int class_number;
    struct node* classpointer;
    struct node* studentpointer;
}* nodePtr;

这样可以解决您的问题,因为这些属性并不总是在代码中初始化(new node如果没有这样的构造函数,则不会初始化node属性。)