据我所知,到目前为止;我遇到的问题可能与指针有关。我对C ++比较陌生,虽然我想我知道问题出在哪里,但我很难理解它为什么会发生。
下面是每个存储字符串(称为“数据”)的节点的链接列表的构造函数,我想要一个我可以在链接列表上调用的方法(在main中初始化),最终打印出的内容每个节点。我开始只是尝试打印第一个节点的内容(由root指向),但后来遇到了分段错误错误。我一直在摆弄我的代码并查找在线资源几个小时无济于事。任何意见都将不胜感激。
#include <string>
#include <iostream>
#include "Node.h"
#include "Linked.h"
Linked::Linked(int size){
Node *root; //the start of the linked list, remains static
root = new Node; // sets it to point at a Node
Node *conductor; // This will point to each node as it traverses the list
conductor = root; // The conductor points to the first node
if ( conductor != 0 ) {
while ( conductor->next != 0)
conductor = conductor->next;
}
for (int i = 0; i < size; i++){
//std::cout << conductor->data;
conductor->next = new Node; // Creates a node at the end of the list
conductor = conductor->next; // Points to that node
}
}
void Linked::printMemory(){
int memorycheck[32] = { }; //
Node *conductor; //creates a conductor
conductor = root; //sets conductor to point to the same Node that root does, the issue may occur here. Why?
for (int i = 0; i < 32; i++){
std::cout << conductor->data;
}
这是我的Linked头文件 }
#ifndef LINKED
#define LINKED
#include <iostream>
#include <string>
#include "Node.h"
class Linked {
public:
Node *root;
Linked(int size);
void addProgram (std::string name, int size);
void printMemory ();
};
#endif
答案 0 :(得分:0)
我知道你在构造函数中有问题。
Linked::Linked(int size){
Node *root; //the start of the linked list, remains static
...
}
在此声明变量root
,这与您的类定义中的root
不同!尝试从代码中删除此行。