gpt4 book ai didi

C++ 程序无缘无故结束? (哈希表)

转载 作者:行者123 更新时间:2023-11-27 22:45:08 25 4
gpt4 key购买 nike

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

#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() 函数中,可能在条件中,但我不知道出了什么问题。

最佳答案

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

你在这里做的是获取 list 并检查它指向的值是否为 NULL,但是因为你还没有检查 if (list ) 那么 list == NULL 可能会在取消引用时导致段错误

关于C++ 程序无缘无故结束? (哈希表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43976915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com