[英]“Exception thrown: read access violation. this->head was nullptr.”
I'm writing code that removes every other element from a Linked List.我正在编写从链接列表中删除所有其他元素的代码。 It works when there are enough elements in the List.
当列表中有足够的元素时,它会起作用。 When there are not enough elements, I'm trying to still have the code run through a
while
loop for other options (add, remove, etc).当没有足够的元素时,我仍然试图让代码通过
while
循环运行其他选项(添加、删除等)。 However, an error pops up但是,会弹出一个错误
Exception thrown: read access violation.
抛出异常:读取访问冲突。 this->head was nullptr.
this->head 是 nullptr。
How would I fix this?我将如何解决这个问题? I provided the function below:
我在下面提供了 function:
void removeEveryOtherNode() {
Chunk* previous = head;
Chunk* pointer = head->next; //error happens here
if (head == NULL) {
cout << "Linked List is empty...Nothing to delete" << endl;
}
else if (pointer == NULL) {
cout << "Not enough elements to delete every other element." << endl;
}
while (previous != NULL && pointer != NULL) {
previous->next = pointer->next;
delete pointer;
previous = previous->next;
if (previous != NULL) {
pointer = previous->next;
}
}
cout << "Removed every other element. Press 4 to display" << endl;
}
You should check if head is valid before dereferencing it您应该在取消引用之前检查 head 是否有效
if (head == NULL) {
cout << "Linked List is empty...Nothing to delete" << endl;
return;
}
if (head->next == NULL) {
cout << "Not enough elements to delete every other element." << endl;
return;
}
// then dereference
Chunk* pointer = head->next;
Also, use nullptr
instead of NULL
.此外,使用
nullptr
代替NULL
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.