我只是回到编码。已经好几年了我不知道为什么这会引发nullptr访问冲突。我已经将其压缩为一行代码。当我尝试将我的第二个条目(newNode的pLast指针)设置为head时,将引发冲突。
我正在尝试根据执行的搜索(也称为countVar)创建带有气泡排序的双向链表。任何帮助都会很棒。
#include <iostream>
#include <stdlib.h>
using namespace std;
//build class that has a private function to inc count.
class LinkedListCount {
private:
struct CountNode {
int data;
int countVar; //Make the variable "countVar" private to protect integrity.
CountNode* pNext = NULL;
CountNode* pLast = NULL; //Needed for bubbling back through list.
};
//Keep track of head
CountNode* head;
CountNode* current;
CountNode* temp;
public:
//Constructor Function (Set default values for head, current, and temp)
LinkedListCount() {
head = NULL;
current = NULL;
temp = NULL;
}
void AddNode(int dataIn) { //Addnode Function
//Create and populate list.
CountNode* newNode = new CountNode;
newNode->pNext = NULL;
newNode->pLast = NULL;
newNode->data = dataIn;
temp = head;
newNode->countVar = 0;
if (temp != NULL) { //We already have data entery.
if (temp->pNext == NULL) {
newNode = temp->pNext;
newNode->pLast = head; //****THIS IS WHERE ACCESS VIOLATION OCCURES
}
//Set variables with the understanding that the head is the only data point.
else {
current = temp->pNext; //Set it equal to head.
}
while (current->pNext != NULL) {//This could be eliminated with keeping track of a tail.
current = current->pNext; //Attach this to the end of the list.
}
current->pNext = newNode; //And newMode->pNext = to Null so next time I add data I'll get to the end of the list.
newNode->pLast = current;
}
else if (head == NULL) {
head = newNode;
}
}
};
void addNodes(LinkedListCount &DataList) { //Populates list.
for (int i = 0; i < 20; i++) {
DataList.AddNode(i);
}
}
int main(void)
{
addNodes(DataList);
}
最佳答案
if (temp->pNext == NULL) { // temp->pNext is NULL
newNode = temp->pNext; // newNode is now NULL too
newNode->pLast = head; // attempt to use pLast of NULL
}
我已经在您的代码中添加了注释,以查看您为什么遇到访问冲突。
关于c++ - 引发: write access violation. newNode was nullptr异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57933050/