简体   繁体   English

C ++链接列表指向结构崩溃的指针

[英]C++ Linked List Pointer to Struct Crashing

When I call the default constructor for my class LinkedList I attempt to assign values to the head node of the linked list before any other operations occur. 当我为我的类LinkedList调用默认构造函数时,我尝试在发生任何其他操作之前将值分配给链表的头节点。 I have isolate the error, via debugging, to the instructions in the default constructor. 我已经通过调试将错误与默认构造函数中的指令隔离开来。 As soon as 立刻

    head -> next = NULL;
    head -> RUID = 0;
    head -> studentName = "No Student in Head";

are called the program crashes. 被称为程序崩溃。 This occurs when I call the default constructor in main. 当我在main中调用默认构造函数时会发生这种情况。 Here is my class declaration and my struct declaration along with the default constructor: 这是我的类声明和我的结构声明以及默认构造函数:

struct Node
{
    string studentName;
    int RUID;
    Node* next;
};

class LinkedList
{
private:

    // Initialize length of list 
    int listLength;

public:
    // Head of the list, which points to no data yet
    Node *head;
    LinkedList();
    bool insertNode(Node* newNode, int position);
    int generateRUID(); 

};


LinkedList::LinkedList()
{

    head -> next = NULL;
    head -> RUID = 0;
    head -> studentName = "No Student in Head";

    listLength = 0; 
}

I believe this all of the relevant code to this issue. 我相信这个问题的所有相关代码。 If someone could shed light on this it would be much appreciated. 如果有人能够阐明这一点,我将不胜感激。

LinkedList::head is a Node* , not a Node and you don't initialize it, so the object (binary, in-memory) representation is undefined and is therefore dangerous to dereference. LinkedList::head是一个Node* ,而不是一个Node ,你没有对它进行初始化,因此对象(二进制,内存中)表示是未定义的,因此对解除引用很危险。

Change your LinkedList to explicitly initialize the head member. 更改LinkedList以显式初始化head成员。 I recommend storing it by-value (as Node ) rather than as a heap-allocated value ( Node* ) for simplicitly, unless you know you'll need to reparent nodes. 我建议将它按值(作为Node )而不是作为堆分配值( Node* )存储,除非您知道您需要重新显示节点。

Using Node* : 使用Node*

LinkedList::LinkedList() :
    head( Node() ),
    listLength( 0 )
{
    this->head->next = nullptr;
    this->head->RUID = 0;
    this->head->studentName = "No Student in Head";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM