![](/img/trans.png)
[英]Exception thrown: read access violation. this->m_pRenderTarget was nullptr. c++
[英]“Exception thrown: read access violation. this->head was nullptr.”
我正在編寫從鏈接列表中刪除所有其他元素的代碼。 當列表中有足夠的元素時,它會起作用。 當沒有足夠的元素時,我仍然試圖讓代碼通過while
循環運行其他選項(添加、刪除等)。 但是,會彈出一個錯誤
拋出異常:讀取訪問沖突。 this->head 是 nullptr。
我將如何解決這個問題? 我在下面提供了 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;
}
您應該在取消引用之前檢查 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;
此外,使用nullptr
代替NULL
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.