【问题标题】:Hashtable crashes when retrieving value from table index从表索引中检索值时 Hashtable 崩溃
【发布时间】:2015-07-30 23:02:20
【问题描述】:

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

数据类:

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

}

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

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

哈希表类

   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]-&gt;item.GetName() 执行GetName() 时崩溃,如果我这样做table[index]-&gt;item.GetName(),程序也会崩溃。如果我测试table[index] == NULL,我不会收到任何错误。

【问题讨论】:

    标签: c++ hashtable


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      相关资源
      最近更新 更多