【问题标题】:C++ program ends for no reason ? (Hash table)C++程序无缘无故结束? (哈希表)
【发布时间】:2017-05-15 10:18:11
【问题描述】:

我正在尝试使用单独的链接冲突解决方案来实现哈希表,但我遇到了问题。 这是我的代码(稍作修改以简化,但错误仍然相同):

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
using namespace std;

int ascii(char character)
{
    return character;
}

int hashFunction(string word, int num)
{
    char* str = new char[word.length() + 1];
    strcpy(str, word.c_str());
    return ((3 * ascii(str[0]) + 5 * ascii(str[1]))) % num;
}

typedef struct tab
{
    string data;
    struct tab* next;
}Node;

typedef struct link
{
    Node* head;
    Node* tail;
}List;

List* createList()
{
    List* list = new List();
    if (list)
    {
        list->head = NULL;
        list->tail = NULL;
    }
    return list;
}

void insert(List* list, string data)
{
    //if list is empty
    if (list->head == NULL) //!!!!!!!!!!!!!!!!ERROR OCCURE HERE !!!!!!!!!!!!!!!
    {
        list->head = new Node();
        list->head->data = data;
        list->head->next = NULL;
        list->tail = list->head;
    }
    //if list already contains some data
    else
    {
        list->tail->next = new Node();
        list->tail->next->data = data;
        list->tail = list->tail->next;
        list->tail->next = NULL;
    }
}

int main(int argc, char* argv[])
{   
    int size = 8; //Size of hash table (number of indexes)

    List* table[12];

    string A[8] = {     "hello","world","car","notebook","science","starwars","lollypop","anything" };

//Insert elements from array A into a hash table
int index;
for (int i = 0; i < size; i++)
{
    index = hashFunction(A[i], size);
    if (table[index] == NULL)
        table[index] = createList();
    insert(table[index], A[i]);
}

return 0;
}

当我运行 .exe 文件(或从 cmd 启动)时,程序结束时显示 app.exe 已停止工作的消息。我尝试调试程序并得到了这个: http://imgur.com/a/yOhRV

谁能帮我解决这个问题?我发现问题一定出在 insert() 函数中,可能在条件中,但我不知道出了什么问题。

【问题讨论】:

  • 欢迎来到 Stack Overflow!听起来您可能需要学习如何使用debugger 来单步执行您的代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。进一步阅读:How to debug small programs.

标签: c++ hashtable


【解决方案1】:

你取消引用一个指针而不检查它:if (list-&gt;head == NULL)...

您在这里所做的事情是使用list 并检查它所指向的值是否为NULL,但由于您尚未检查if (list),那么list == NULL 可能会在取消引用时导致段错误它

【讨论】:

    【解决方案2】:

    您声明了List* table[12],但它从未被初始化。所以它确实包含垃圾。

    您必须执行以下操作才能对其进行初始化:List* table[12] = {NULL};

    【讨论】:

      【解决方案3】:

      作为一般规则,您的代码中永远不应包含未初始化的变量(除非出于优化目的,当您确切知道自己在做什么时)。

      将默认构造函数添加到您的结构并使用初始化列表。还要尽可能让变量保持本地化(在循环内移动索引)。​​

      你不需要 ascii() 因为 char 是整数类型。 char+char 和 char*int 被提升为 int。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多