【发布时间】:2018-09-18 16:45:14
【问题描述】:
这是一个简单的 C++ 链表程序。我面临的问题是,当我运行我的代码时,它会获取第一个数据,但接下来会显示异常错误。我在 Visual Studio 2017 上运行此代码。我尝试了很多,但无法理解代码的原因无法工作。
#include<iostream>
using namespace std;
struct Node {
int data;
Node *next;
}*head = NULL, *temp = NULL , *temp1 = NULL;
Node* Create_New_Node(int);
int Insert(Node *);
Node* Create_New_Node(int a)
{
Node *np = new Node;
np->data = a;
np->next = NULL;
return np;
}
int Insert(Node *np)
{
if (head == NULL) {
head = np;
return 0;
}
temp1 = head;
while(temp1 != NULL) {
temp1 = temp1->next;
}
temp1->next = np;
}
int main()
{
char ch = 'y';
int inf;
while (ch == 'y' || ch == 'Y')
{
system("cls");
cout << "Enter data : " << endl;
cin >> inf;
temp = Create_New_Node(inf);
Insert(temp);
cout << "Press y to continue " << endl;
cin >> ch;
}
system("pause");
return 0;
}
这是错误输出:
'Project2.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ucrtbased.dll'. Symbols loaded.
'Project2.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcp140d.dll'. Symbols loaded.
Exception thrown: write access violation.
**temp1** was nullptr.
The program '[10588] Project2.exe' has exited with code 0 (0x0).
由于我是 C++ 链表概念以及 Stack Overflow 的新手,有人可以帮我编写代码吗?无论哪里出错,请纠正我谢谢。
【问题讨论】:
标签: visual-c++ c++14