【发布时间】:2019-07-20 04:20:30
【问题描述】:
我在visual studio 2013中为双向链表编写了一个程序,它在标有注释的行抛出了未处理的异常错误:-
linked_list_double.h:-
#pragma once
#include<iostream>
template <typename T>
struct Node
{
T data;
Node *next, *prev;
};
template <typename T>
class doubleLinkedList
{
private:
Node<T> *top;
public:
doubleLinkedList()
{
top = nullptr;
}
void add(T data)
{
Node<T> *temp = new Node<T>;
temp->prev = nullptr;
temp->next = top;
top->prev = temp; //unhandled exception here
top = temp;
}
void display()
{
Node<T> *temp;
temp = top;
std::cout<<"nullptr<--->\n";
while(temp)
{
std::cout<<temp->data<<"<--->";
temp = temp->next;
}
std::cout<<"nullptr\n";
}
};
main.cpp: -
#include "linked_list_double.h"
int main()
{
doubleLinkedList<int> L;
L.add(3);
L.add(4);
L.display();
return 0;
}
错误是:-
Unhandled exception at 0x011C4B79 in dataStructures2.exe: 0xC0000005: Access violation writing location 0x00000008.
我以前从未写过双向链表。我不确定程序中是否有任何逻辑错误。任何形式的帮助将不胜感激。
【问题讨论】:
-
重现问题的
main()函数在哪里?请发帖minimal reproducible example -
另外,你为什么不调试你的代码?没有理由不调试代码,因为您使用的是 Visual Studio,它拥有世界上最好的调试器之一,并且“调试”选项就在 IDE 的主菜单上。如果您这样做了,您应该会看到
top是一个空指针,并且您正在尝试取消引用它。 -
我没想到。谢谢。
标签: c++ visual-studio data-structures linked-list