从 table 索引检索值时哈希 table 崩溃

Hashtable crashes when retrieving value from table index

我正在尝试使用哈希表实现一个简单的 adt,我能够将数据对象插入到它们各自的索引中。当我尝试检查 table[index]->data.GetName() 中的值时,程序崩溃了。

数据class:

Data(string name, string value int value = 0) : name(name), value(value)
{

}

string Data::GetName() const
{
    return name;
}

string Data::GetValue() const
{
    return value;
}

散列TableClass

   class HashT
{
public:
    HashT(ostream&) : size(0), cap(TBL_CAP), table(new hashnode*[TBL_CAP])
    {
        for (int i = 0; i < cap; ++i)
        {
            table[i] = NULL;
        }
    };
    HashT()
    {
    };
    //~HashT();
    void HashT::Ins(Data& data)
    {
        size_t index = HashFunc(data.GetName());
        node * newData = new node(data);
        //if (table[index]->item.GetName() == data.GetName())
        // Do not insert;
        else
            newData->next = table[index];
            table[index] = newData;
            size++;
    }
    int  HashFunc(string name);

private:

    struct hashnode
    {
        Data item;
        hashnode* next;
        node(const Data& DataObj) : item(DataObj), next(NULL)
        {

        }
    };
    hashnode ** table;
    int size;
    Data data;
    int cap;

    const static int TBL_CAP = 3;
};

当我调试时,程序在 item 尝试通过 table[index]->item.GetName() 执行 GetName() 时崩溃,如果我执行 table[index]->item.GetName() ,程序也会崩溃。如果我测试 table[index] == NULL,我不会收到任何错误。

table[index] 可能为 NULL(并且绝对是您第一次开始添加数据时)。这意味着您无法访问 table[index]->item,因为那将是 NULL 指针取消引用。您在检查 NULL 方面走在了正确的轨道上——您需要同时执行这两项操作,检查 NULL,然后检查名称。您可以按如下方式在一次 if 测试中执行此操作:

if (table[index] != NULL && table[index]->item.GetName() == data.GetName())