【发布时间】:2020-07-22 06:53:31
【问题描述】:
我有一个问题,应用程序在函数内部引用 if(!head) 的代码行崩溃:insertNode()。 head 和 tail 是 node* 类型的类成员。看起来,我在类成员的方式上遗漏了一些东西:头、尾的初始化.. 这是运行时错误:“SLinkedlist_array.exe 中 0x00245246 处的未处理异常:0xC0000005:访问冲突读取位置 0x00000000。”
slinkedlist.h:
typedef struct node
{
int value;
struct node* next;
} node;
class slinkedlist
{
public:
//ctor, dtor, insertNode(int, int), displayList()
private:
node* head, tail;
};
slinkedlist.cpp:
bool slinkedlist::insertNode(int value, int aftNodeVal)
{
int toinsertval = value;
int searchkey = aftNodeVal;
bool retval = false;
// If it's a new linked list
if(!head) // THIS IS WHERE THE APPLICATION CRASHES!
{
node* head = new node;
head->value = toinsertval;
head->next = NULL;
return true;
}
else //It's not a new list
{
while(head->next != NULL)
{
//some more code here...
}
}
return retval;
}
void slinkedlist::displayList()
{
while(!head)
{
do
{
cout << head->value << " " ;
head = head->next;
}
while(head->next != NULL);
}
//return void;
}
main.cpp:
int main()
{
slinkedlist *s1 = NULL;
s1->insertNode(4, -1);
s1->displayList();
while(1);
}`
【问题讨论】:
-
你
s1->insertNode(4, -1);,但是s1还没有初始化。 -
无关:
typedef struct node { int value; struct node* next; } node;的typedefing 不是必需的。 C++ 非常聪明,可以弄清楚没有它的节点是什么。struct node { int value; struct node* next; };就足够了。 -
相关:阅读Member Initializer List。
-
根据您定义变量的方式和位置,它可能会或可能不会被初始化。 Some reading on those rules。在这种情况下,你是对的,问题是初始化。
head和tail没有被初始化。 Here's a link to documentation on the may different ways you can initialize in C++。选择一个最有意义的。但是……
标签: c++ visual-studio class crash runtime