gpt4 book ai didi

c++ - 令人沮丧的指针错误

转载 作者:太空宇宙 更新时间:2023-11-04 15:41:00 26 4
gpt4 key购买 nike

对于我的生活,我无法弄清楚出了什么问题。我知道错误发生在下面标记为 displayQueue 的函数中,但所有语法和逻辑似乎都是正确的。

Visual Studio 给我错误:“ex11_1.exe 中 0x00215A86 处未处理的异常:0xC0000005:访问冲突读取位置 0xCDCDCDE1。”但实际上,我不知道这是指什么...

#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;

struct QueueNode {
string data;
QueueNode *link;
};
typedef QueueNode* QueueNodePtr;


class Queue {
public:
// Constructors/Destructor.
Queue();
Queue(const Queue& aQueue);

// Accessors.
bool empty() const;
void displayQueue ();

// Mutators.
void add(string item);
string remove(); // This should probably be replaced with pop and top - especially for displayQueue... empty() in functions can be replaced with count == 0. Yes, I will do this.

private:
QueueNodePtr front; // Points to head of linked-list queue.
QueueNodePtr back; // Points to tail of linked-list queue.
size_t count;
};

int main () {
Queue myQueue;

myQueue.add("abc");
myQueue.add("def");
myQueue.add("ghi");

myQueue.displayQueue(); // The error is here somewhere. abc is printed and but nothing else.

system("pause");
return 0;
}

Queue::Queue() {
front = NULL;
back = NULL;
count = 0;
}

Queue::Queue(const Queue& aQueue) {
front = aQueue.front;
back = aQueue.back;
count = aQueue.count;
}

bool Queue::empty() const {
if (count == 0) {
return 1;
} else {
return 0;
}
}

void Queue::displayQueue () {
// There is a problem here somewhere...

QueueNodePtr here = front;
for (int i = 0; i < count; i++) {
cout << here->data << endl;
here = here->link;
}
}

void Queue::add(string item) {
QueueNodePtr newNode;
newNode = new QueueNode;

if (count == 0) {
// If inserted in an empty queue, back and front point to same element.
newNode->data = item;
// newNode->link = NULL; // Not sure this part is even necessary.
back = newNode;
front = back;
} else {
// Otherwise, leave front pointer where it's at.
newNode->data = item;
newNode->link = back->link;
back = newNode;
}
count ++;
}

string Queue::remove() {
string returnString;

if (count == 0) {
return returnString;
} else if (count == 1) {
returnString = front->data;
front = NULL;
back = front;
count--;
return returnString;
} else {
returnString = front->data;
front = front->link;
count--;
return returnString;
}
}

编辑:如果有人能给我任何关于使用调试器解决此类问题的提示,或者给我一个可能解释这个问题的链接,我将不胜感激。

最佳答案

错误就在这一行,但是为了学习,我就不给出正确的版本了,只是一些提示:

newNode->link = back->link;

在执行这段代码的时候,back 指向哪个节点?它的 link 指向什么?您需要修改谁节点的链接

至于自己找到这个问题,您可以使用调试器找出导致崩溃的行;这表明 link 值有问题。

附言您的复制构造函数实际上并不复制链表;它只是创建一个指向同一个链表的新 Queue 对象,因此如果您向拷贝添加一个元素,它将显示在原始 Queue 中。

关于c++ - 令人沮丧的指针错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23164705/

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