【发布时间】:2018-12-24 00:38:15
【问题描述】:
我可以到达添加节点的位置,但在那之后,程序就会自行关闭。
我在 Windows 10 上,使用 VSCode 内部人员。使用 G++ 作为我的编译器,如果有的话。我试过手动设置节点的指针,这很有效。我无法弄清楚该方法有什么不同。这个想法是“tail是最后一个节点,所以将tail.next设置为添加的节点并将tail设置为新节点。”
#include <iostream>
using namespace std;
struct Node{
int data;
struct Node *next;
};
class List{
private:
struct Node *head;
struct Node *tail;
public:
list(){
head->next=tail;
// I tried initializing tail.next to null but that didn't help
tail->next=NULL;
}
void add(int d){
printf("I'm entering the add\n");
struct Node *n=new Node;
printf("Node created\n");
n->data=d;
printf("Data set %d\n", n->data);
// right here is the issue, it seems
tail->next=n;
printf("Node added\n");
tail=n->next;
}
};
int main(){
List l;
l.add(50);
return 0;
}
我希望它打印 50(我还没有尝试过我的显示方法,因为代码在到达那里之前就中断了),但是它输出“Data Set 50”然后崩溃。编译正常,没有警告。
【问题讨论】:
-
您在构造函数中取消引用未初始化的指针。
-
另外,这不会按原样编译;当您修复错字时,编译器会通过正确的设置警告您。至少 gcc 可以。 wandbox.org/permlink/7pl4kRUZ6de8ulEw
-
Baum Mit Augen- 这很奇怪,在这里编译得很好。虽然我很困惑你为什么使用 gcc- 那也编译 c++ 吗?我将如何解决取消引用?
-
它不应该编译;您可能在将其传输到页面时搞砸了。我在这里使用“gcc”作为 GNU 编译器集合的缩写;当然,您可以使用 C++ 代码的 g++ 命令调用它。最后,您可以通过不这样做来修复取消引用。重新思考代码的逻辑。
-
我没有编译因为你使用了类
List然后将你的构造函数命名为list。c++区分大小写,所以这些是不同的东西。
标签: c++ class linked-list