【问题标题】:Template variable assignment segment fault 11 [closed]模板变量赋值段错误 11 [关闭]
【发布时间】:2016-04-21 04:35:24
【问题描述】:

我目前正在为学校做一个哈希表项目,我遇到了一个我无法弄清楚的问题。我的教授为我们提供了具有我们需要实现的功能的类,这些功能使用模板。

无论如何,在我的插入函数中,我遇到了在用于实现哈希表的单链表结构中设置节点值的问题。

我的问题是这样的:

void insert(U item1, U item2){  //For my project U is a string
    Node<U>* temp = headPtr;

    cout << item1 << endl; //Will print out the string no problem

    //Assignment attempt
    temp->SSN = item1; // causes a seg fault


    temp->name = item2;
    temp->next = NULL;
    if(headPtr->next == NULL){
        headPtr->next = temp;
        size++;
    }
    else{
        Node<U>* temp2 = headPtr;
        while(temp2->next != NULL){
            temp2 = temp2->next;
        }
        temp2->next = temp;
        size++;
    }
}

这非常令人沮丧,因为在以前的作业中我已经能够正确使用这个插入功能,我得出的结论是它不起作用的唯一原因是因为我必须在模板中遗漏一些我忽略的东西。

这也是我的 node.h 文件:

 #include <iostream>
 using  namespace  std;

 template <class T>
 struct  Node{
 T SSN;
 T name;
 Node<T>*  next;
 };

我正在尝试将一个字符串值分配给应该是一个字符串值,并且据我的理解应该可以工作,但是每次我运行程序时它都会到达这一点并且只有段错误 11。

【问题讨论】:

  • headPtr 是否声明为Node&lt;U&gt;* 并包含调用new Node&lt;U&gt; 的结果

标签: c++ templates pointers hashtable singly-linked-list


【解决方案1】:

你必须更换

  Node<U>* temp = headPtr;

  Node<U>* temp = new Node<U>;

【讨论】:

  • 成功了,谢谢。这是有道理的,我所指的节点是 NULL,所以它不能在那里有值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 2019-10-08
  • 1970-01-01
  • 2013-06-20
  • 1970-01-01
相关资源
最近更新 更多