【问题标题】:Insertion on a hash table在哈希表上插入
【发布时间】:2015-06-10 05:12:47
【问题描述】:

我正在尝试编写一个程序来创建一个处理与链表冲突的 hash_table。链表将由一个由 2 个字符组成的结构组成。 我想在链表的开头插入这种类型的结构,但是我一直在一行上出现段错误,我不明白为什么。 这是我的代码:

typedef struct celula       //this is the chained list structure
{
    struct celula *urm;
    void *info;
} TCelulaG, *TLG;

typedef struct  //this is the hash_table structure      
{
    size_t M;
    TLG * v;
} TD;

typedef struct   // the structure that should be inserted
{
    char *key;
    char *value;
} TDate;

我有一个哈希函数和一个初始化函数(将表的每个参数设置为 null ),效果很好。

现在插入函数:

int put(TDate element, TD * hash_table,size_t M)    
{
    TLG it,aux,ant;                     
    size_t h=hash(element.key,M);   
    it=(TLG)malloc(sizeof(TCelulaG));           
    it= hash_table->v[h];   
    it->info=(TDate*)malloc(sizeof(TDate));   //this is the line that causes the segfault

    it = hash_table->v[h];
    if(it==NULL)                        
    {
        ((TDate*)((it)->info))->key=element.key;
        ((TDate*)((it)->info))->value=element.value;
        it->urm=hash_table->v[h];
        hash_table->v[h]=it;
        return 1;
    }
}

【问题讨论】:

  • 确保it 不为空

标签: c hashtable


【解决方案1】:

确保it 不为空。

你为什么分配给it,然后从hash-table->v[h] 分配。 hash_table->v[h] 很可能是空的,因此是段错误。在分配给it->info 之前检查it

【讨论】:

    猜你喜欢
    • 2015-06-25
    • 2017-03-28
    • 1970-01-01
    • 2014-11-01
    • 2015-11-08
    • 2015-03-07
    • 2023-03-04
    • 2011-11-22
    相关资源
    最近更新 更多