在将第一个值插入链表时尝试访问 head 时出现分段错误
Segment fault on trying to access head while inserting first value into linked list
我一整天都在工作,不仅要做这个作业,还要做其他 3 个作业(针对同一类(,这是我自己无法弄清楚的最后一个问题,我是模板新手,所以不太确定它们是如何工作的 100%。
没有模板,这段代码可以完美运行,但是使用模板,我在if(head == NULL)
的prioqueueUNS
文件中收到分段错误,我无法弄清楚为什么会发生这种情况,因为我默认head
在构造函数中NULL
,因此任何帮助将不胜感激
int main
#include "node.h"
#include "prioqueueUNS.cpp"
int main() {
PrioQueueUNS<int> list;
list.insertItem(1);
}
节点.h
#ifndef node_h
#define node_h
using namespace std;
template<class Type>
struct node {
Type data;
node<Type> *next;
};
#endif
prioqueueUNS.cpp
#ifndef prioqueueUNS_cpp
#define prioqueueUNS_cpp
#include "node.h
using namespace std;
template<class Type>
class PrioQueueUNS {
private:
node<Type> *head;
node<type> *tail;
int sizee;
int size;
int min;
public:
PrioQueueUNS() {
head = NULL;
tail = NULL;
}
PrioQueueUNS(Type *dataArray, int n) {
head = NULL;
tail = NULL;
}
void insertItem(Type n) {
node<Type> *temp;
temp->data = n;
temp->next = NULL;
if (head == NULL) { //<-- segment faulting when trying to access head
head = temp;
tail = temp;
min = n;
}
}
};
node<Type> *temp;
temp->data = n;
你创建了一个指针(temp
(,但它什么都不指向,所以temp->data
尝试访问不存在的东西的data
字段。
您可以使用new
解决此问题,但这需要您事后销毁对象。
您从不为节点分配内存。指针温度的声明也不正确:-
node<Type> *temp;// temp is a pointer only you have to allocate memory first
temp->data = n;
temp->next = NULL;
更正如下:-
对于整数:-
node<int> *temp = new node<int>();
对于一个浮标:-
node<flot> *temp = new node<flot>();
在以下声明中也更正:-
node<type> *tail; to node<Type> *tail;
相关文章:
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- 用于访问容器<T>数据成员的正确 API
- 访问者访问变体并返回不同类型时出错
- 尝试通过多个向量访问变量时,向量下标超出范围
- 无法访问嵌套类.类的使用无效
- 写入位置0x0000000C时发生访问冲突
- 我们可以访问一个不存在的联盟的成员吗
- C++从另一个类访问公共静态向量的正确方法是什么
- 我的简单if-else语句是如何无法访问的代码
- 从C++dll访问C#中的一行主要参数
- 概念TS检查忽略私有访问修饰符
- 访问被拒绝后,c++中的故障保护代码
- 在c++中访问int到类对象的映射时出错
- 我想访问std::unique_ptr中的一个特定元素
- 为什么示例代码访问IUnknown中已删除的内存
- C++:无法访问声明的受保护成员
- 通过指向指针数组的指针访问子类的属性
- 在将第一个值插入链表时尝试访问 head 时出现分段错误