我正在尝试实现哈希表,但在 createHashTable() 函数的 for 循环中遇到运行时错误。谁能告诉我为什么会显示这个“运行时错误”?是 StackOverflow 错误吗?
#include <iostream>
using namespace std;
#define LOAD_FACTOR 20
struct ListNode{
int data;
struct ListNode *next;
};
struct HashTableNode{
int bCount; // number of elements in the block
struct ListNode *next;
};
struct HashTable{
int tSize; // table size
int count; // total number of elements in the table
struct HashTableNode **hashTableNodeArray;
};
int hashFunction(struct HashTable *h, int data){
return data % h->tSize;
}
struct HashTable * createHashTable(int numberOfElements){
struct HashTable *h = new HashTable;
h->count = 0;
h->tSize = numberOfElements / LOAD_FACTOR;
h->hashTableNodeArray = new HashTableNode *[h->tSize];
for(int i = 0; i < h->tSize; ++i){
// this is where it is showing runtime error
h->hashTableNodeArray[i]->bCount = 0;
h->hashTableNodeArray[i]->next = nullptr;
}
return h;
}
void deleteHashTable(struct HashTable *h){
struct ListNode *node, *tmp;
for(int i = 0; i < h->tSize; ++i){
node = h->hashTableNodeArray[i]->next;
while(node != nullptr){
tmp = node;
node = node->next;
delete tmp;
}
}
delete[] h->hashTableNodeArray;
delete h;
}
int main(int argc, char **argv){
struct HashTable *h = createHashTable(220);
deleteHashTable(h);
return 0;
}
最佳答案
h->hashTableNodeArray = new HashTableNode *[h->tSize];
这分配了一个指针数组,但不是实际的哈希表节点。在下面的循环中,您尝试写入它们,这是未定义的行为。
你在你的循环中丢失了:
h->hashTableNodeArray[i] = new HashTableNode;
关于c++ - 谁能告诉我为什么显示 "runtime error"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28344524/