gpt4 book ai didi

c++ - 抛出异常 : write access violation. newNode 为 nullptr

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:38:01 27 4
gpt4 key购买 nike

我刚刚重新开始编码。已经有几年了。我不明白为什么会引发 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 为 nullptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57933050/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com