我总是遇到分段错误
i am always getting segmentation fault
我总是在 C++ 中遇到 10861 分段错误(核心已转储)抱歉,我来自 java
它总是说 head -> next 如何分配内存给那个
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
};
class lisp
{
public:
Node *head;
void create(int d)
{
this->head->data = d;
cout << head->data;
}
void insert(int d)
{
Node *n = head;
Node *add;
add->data = d;
cout << head -> next << endl;
}
};
int main()
{
lisp test;
test.create(0);
test.insert(1);
test.insert(2);
return 0;
}
您需要先初始化指针,然后再为其赋值。因此,您需要 Node *add = new Node();
才能这样做。假设您想将一个新节点附加到列表中,也许您需要跟踪列表的尾部 (Node *tail
)。每次添加新节点时,都会移动 tail
.
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
};
class lisp
{
public:
Node *head;
Node *tail;
void create(int d)
{
head = new Node();
head->data = d;
tail = head;
cout << head->data << endl;
}
void insert(int d)
{
Node *add = new Node();
add->data = d;
add->next = NULL;
tail->next = add;
tail = add;
cout << add->data << endl;
}
};
int main()
{
lisp test;
test.create(0);
test.insert(1);
test.insert(2);
return 0;
}
我总是在 C++ 中遇到 10861 分段错误(核心已转储)抱歉,我来自 java 它总是说 head -> next 如何分配内存给那个
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
};
class lisp
{
public:
Node *head;
void create(int d)
{
this->head->data = d;
cout << head->data;
}
void insert(int d)
{
Node *n = head;
Node *add;
add->data = d;
cout << head -> next << endl;
}
};
int main()
{
lisp test;
test.create(0);
test.insert(1);
test.insert(2);
return 0;
}
您需要先初始化指针,然后再为其赋值。因此,您需要 Node *add = new Node();
才能这样做。假设您想将一个新节点附加到列表中,也许您需要跟踪列表的尾部 (Node *tail
)。每次添加新节点时,都会移动 tail
.
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
};
class lisp
{
public:
Node *head;
Node *tail;
void create(int d)
{
head = new Node();
head->data = d;
tail = head;
cout << head->data << endl;
}
void insert(int d)
{
Node *add = new Node();
add->data = d;
add->next = NULL;
tail->next = add;
tail = add;
cout << add->data << endl;
}
};
int main()
{
lisp test;
test.create(0);
test.insert(1);
test.insert(2);
return 0;
}