【问题标题】:Hash table implementation for storing strings用于存储字符串的哈希表实现
【发布时间】:2012-10-18 13:07:05
【问题描述】:

这是我用于存储字符串值的哈希表的代码。要在我的“插入”函数中使用线性探测,我需要检查指针在该特定哈希值处是否为 NULL。我还没有完成我的插入函数,但是我被卡住了,因为当我在插入函数中检查 if(the_hash_table[n]==NULL) 时,它没有进入分支。如果我打印“the_hash_table[1]”,在散列值之前,它会打印“faz”,但是在我打印它的那一步之后,它会打印一些奇怪的字符。我哪里出错了?

 #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    /*
    creates a hash table of size 10
    */

    char** create_hash_table(){



        char* the_hash_table[10];   // defines a hash table to store strings

        *the_hash_table=malloc(sizeof(char*)*10); // allocates memory in the heap for the hash table
        int i;
        for(i=0;i<10;i++){ // this loop initializes the string pointers to NULL at the starting point of the hash table
            the_hash_table[i]=NULL;
        }
        return &the_hash_table; // returns the address of the hash table to the main memory

    }

    /*
    this is a method to insert a string into the relevant position of the hash table
    */

    void insert(char* the_string,char** the_hash_table){

        printf("%s",the_hash_table[1]);
        int n=hash(the_string);
        printf("%s",the_hash_table[1]);
        if(the_hash_table[n] == NULL)
            the_hash_table[n]=the_string;

    }

【问题讨论】:

    标签: c hashtable


    【解决方案1】:

    你没有正确分配内存。

    您将一个自动变量the_hash_table 定义为一个指针数组。您分配一些内存并将指向该内存的指针放入数组中。您立即用空指针覆盖该指针(以及the_hash_table 的其他元素)。

    然后你返回一个指向本地数组的指针,但是一旦函数退出,这个数组就不再存在了。从定义的函数返回指向自动变量的指针是总是错误的。

    你应该做的是:

    char** create_hash_table(void) {
        char** the_hash_table = malloc(sizeof(*the_hash_table) * 10);
        for (int i = 0; i < 10; ++i) {
            the_hash_table[i] = NULL;
        }
        return the_hash_table;
    }
    

    所以,the_hash_table 是一个指向分配内存的局部变量。您返回它的值,即分配的内存的地址。然后在main 你会free(the_hash_table) 而不是free(*the_hash_table)

    此外,在您的 hash 函数中,复制字符串是没有意义的:只需从 the_string[i] 读取字符即可。即使复制它是有意义的,您为此创建的缓冲区也太小了 1 个字节,它必须是 strlen(the_string)+1,因为 strlen 返回的长度不包括终止字符串。

    【讨论】:

    • 这真的很有帮助。现在我知道我哪里出错了。谢谢你。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    • 2018-03-01
    • 2021-12-30
    • 1970-01-01
    • 2013-12-19
    • 2019-07-29
    相关资源
    最近更新 更多