【发布时间】:2017-11-07 13:26:30
【问题描述】:
我正在尝试为我的链表创建一个函数,该函数将一个节点添加到我的程序末尾。在我的节点中使用链接转发时出现错误
访问冲突读取位置0xccccccd8
它指向我的 add 函数中 while 循环开始处的行。我该如何解决这个问题?
我的添加、打印和显示列表功能:
void List::Add(char data, char* dataString)
{
Node* n5;
n5 = new Node;
n5->data = data;
n5->dataString = dataString;
while (nodes->linkf != NULL)
{
nodes = nodes->linkf;
}
nodes->linkb = n5;
//n5->linkb = List::nodes;
//n5->linkf = NULL;
}
void List::showList(int dir)
{
if (dir==1){
while (nodes !=NULL)
{
Print();
nodes = nodes->linkf;
}
cout<<"\n";
}
if (dir==0){
while(nodes != NULL)
{
Print();
nodes = nodes->linkb;
}
cout<<"\n";
}
}
void List::Print()
{
cout<<" \n";
cout<<nodes->data;
cout<<nodes->dataString;
cout<<" \n";
}
节点和列表类:
class Node
{
public:
Node(){
char data[5];
dataString=new(char[10]);
}
~Node(){};
Node *linkb;
char data;
char* dataString;
Node *linkf;
};
class List{
public:
Node* nodes;
List(){}
void Add(char data, char*dataString);
void showList(int);
void Print();
string entry;
};
主要:
Node *n1, *n2, *n3, *n4 ;
List *l1;
int direction;
char choice;
char data;
char* dataString = "";
char dataBuffer[30];
List myList;
n1 = new(Node);
n2 = new(Node);
n3 = new(Node);
n4 = new(Node);
string entry= "";
l1 =new(List);
cout << "Please input the data: " << endl;
cin >> data;
cout << "Please input the data string: " << endl;
cin >> dataBuffer;
dataString = &dataBuffer[0];
n1->linkb = NULL;
n1->data='C';
n1->dataString="ats ";
n1->linkf = n2;
n2->linkb = n1;
n2->data='L';
n2->dataString="ike ";
n2->linkf = n3;
n3->linkb = n4;
n3->data='F';
n3->dataString="ish ";
n3->linkf = NULL;
n4->linkb = n2;
n4->data='D';
n4->dataString="ont ";
n4->linkf = NULL;
l1->nodes = n1;
myList.Add(data, dataString);
cout<<"\nShow linked list Forward (F) or Backward (B): ";
cin>>choice;
if (choice == 'F')
{
direction=1;
l1->nodes=n1;
l1->showList(direction);
}
else if (choice=='B')
{
direction=0;
l1->nodes=n3;
l1->showList(direction);
}
else
{
cout<<"INVALID ENTRY !";
exit(1);
}
delete (n1);
delete (n2);
delete (n3);
delete (n4);
【问题讨论】:
-
什么是
showList?请发帖minimal reproducible example。 -
使用std::string,而不是char数组和char*!
-
你觉得你在这里做什么?
Node(){ char data[5]; dataString=new(char[10]); } -
@EoinCoogan Visual Studio 拥有最强大和最容易使用的调试器之一。使用它。
-
@EoinCoogan 这个社区没有毒,我们只是在把你推向正确的方向。 VS 调试器是一个很棒的工具,它可以帮助您找出正在发生的事情,它还可以在将来帮助您解决其他问题。你只需要花一些时间(真的不多)来学习调试器的基础知识。在这里倾倒的问题基本上说“我的代码不起作用”通常不会受到欢迎。请阅读此How to Ask。
标签: c++ linked-list