[英]Exception thrown: write access violation. temp was nullptr
我在else
語句中的insert()
函數中遇到錯誤。
這是結構:
struct Node
{
int data;
Node* next;
};
Node* head = NULL;
這是功能:
void insert(int data)
{
Node* New = new Node();
if (head == NULL)
{
New->data = data;
head = New;
}
else
{
// down here where the error occured
Node* temp = new Node();
temp = head;
while(temp != NULL)
{
temp = temp->next;
}
temp->data = data;
temp->next = New;
}
}
你的循環:
while(temp != NULL)
當temp
等於nullptr
時終止(請注意,您最好在 C++ 中使用此常量而不是NULL
),並在該循環之后立即取消引用temp
。 同樣沒有任何理由將new
結果分配給temp
並立即在下一行代碼中釋放它(導致內存泄漏)。 並且您應該始終將data
分配給新項目,而不是temp
(假設是最后一個項目)您的邏輯應該是這樣的:
void insert(int data)
{
Node* New = new Node();
New->data = data; // note you better do these 2 lines in constructor
New->next = nullptr;
if (head == nullptr)
{
head = New;
return;
}
Node* temp = head;
while( temp->next != nullptr ) // look for the last item
temp = temp->next;
temp->next = New;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.