如何解决Hashtable AddEntry 分离链分段错误
我的单独链式哈希表对象出现分段错误。
bool hashTable::addNode(int id,string information){
bool inserted = false;
int position = hash(id);
cout << &hashtable[position]<<endl;
if(hashtable[position]==NULL){
hashtable[position]->data.id = id;
hashtable[position]->data.information = information;
hashtable[position]->next = NULL;
inserted = true;
} else {
Node* current = new Node;
current = hashtable[position];
while(current!=NULL){
if(id < hashtable[position]->data.id){
current->data.id = id;
current->data.information = information;
current->next = hashtable[position];
hashtable[position] = current;
inserted = true;
} else if(id < current->data.id){
current->data.id = id;
current->data.information = information;
current->next = hashtable[position]->next;
hashtable[position]->next = current;
inserted = true;
} else if(current->next==NULL){
Node *temp;
temp->next = NULL;
temp->data.id = id;
temp->data.information = information;
current->next = temp;
inserted = true;
}
current = current->next;
}
}
return inserted;
}
本质上,我有一个头指针数组来处理单独的链接,但是 addNode 中的分段错误让我很困惑。为了清楚起见,我首先调用一个公共 AddEntry,它为数组中的每个单独的 LinkedList 调用 AddNode。
#ifndef HASH_H
#define HASH_H
#include <iostream>
#include <string>
#include "data.h"
using std::string;
using std::cout;
using std::endl;
#define SIZE 15
class hashTable{
public:
hashTable();
~hashTable();
bool addEntry(int id,string information);
string getEntry(int id);
bool removeEntry(int id);
int getCount();
void displayTable();
private:
bool removeNode(int id,int position);
bool addNode(int id,string information);
int count = 0;
Node* hashtable = new Node[SIZE]; //array of head pointers
int hash(int id);
};
#endif
抱歉,如果我没有说出来,这是我第一次使用 Stack Overflow。
解决方法
在您的代码中,有几个地方看起来您似乎错误地使用了取址运算符 &
。让我们从这个开始:
if (&hashtable[position] == NULL) {
...
}
我完全明白你在这里想要做什么 - 你试图说“如果索引 position
处的插槽持有一个空指针。”然而,这不是这段代码的实际作用。这表示“如果内存中存在 hashtable[position]
的位置本身就是一个空指针。”这是不可能的 - hashtable[position]
指的是数组中的一个槽 - 所以这个 if
语句永远不会触发。
在此处绘制图片以更好地了解正在发生的事情可能会有所帮助。例如,假设您有一个空的哈希表,如下所示:
+-------+ +------+------+------+------+ +------+
| |------>| null | null | null | null | ... | null |
+-------+ +------+------+------+------+ +------+
hashtable
这里,hashtable[position]
指的是 position
指向的数组中索引 hashtable
处的指针。对于空的哈希表,hashtable[position]
的计算结果为 NULL
,因为这是该插槽指针的内容。另一方面,&hashtable[position]
指的是这样的:
&hashtable[position]
+-------+
| |
+-------+
|
v
+-------+ +------+------+------+------+ +------+
| |------>| null | null | null | null | ... | null |
+-------+ +------+------+------+------+ +------+
hashtable
这里,&hashtable[position]
指向数组中的一个指针。虽然指针 &hashtable[position]
指向的是空指针,但它本身不是空指针,因为它指向内存中的一个有效对象。
更改代码读取
if (hashtable[position] == NULL) {
...
}
正确表达了“如果 position
数组中索引 hashtable
处的条目不是空指针”的想法。
您的代码在其他几个点也存在类似的错误。仔细阅读您对以下问题的看法:我是否希望将指针存储在数组中的某个索引处,或者我希望指针恰好位于内存中的位置?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。