在将第一个值插入链表时尝试访问 head 时出现分段错误

Segment fault on trying to access head while inserting first value into linked list

本文关键字:head 访问 错误 分段 第一个 插入 链表      更新时间:2023-10-16

我一整天都在工作,不仅要做这个作业,还要做其他 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;