c++ - 谁能告诉我为什么显示 "runtime error"?

标签 c++ c++11

我正在尝试实现哈希表,但在 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/

相关文章:

c++ - 在 std::for_each 中调用 std::function

c++ - 在编译时在 C++ 中生成随机数

c++ - 当类有多个模板参数时专门化成员模板?

c++ - Arduino:无法将取消引用的指针值从库函数返回到草图

c++ - 如何从双数组初始化 Mat?

c++ - 如何将 std::array 转换为 std::vector?

c++11 - boost::variant 和 operator<< 重载

c# - 如何防止操作系统刷新显存

c++ - 尝试使用 OpenCV 从图像写入图像时出现 CL_INVALID_KERNEL_ARGS

c++ - XCODE 产生段错误而不是异常