【问题标题】:Generic hashmaps using c使用 c 的通用哈希图
【发布时间】:2022-01-28 18:25:32
【问题描述】:

我正在尝试在 c 中实现一个通用的 hashmap 但它无法将存储桶插入存储桶列表。 我不知道为什么程序没有任何错误就退出了。 请帮我。 我需要使用这个 hashmap 来为我的 cs 项目实现 LRU 缓存。

typedef struct Bucket Bucket;
struct Bucket
{
    void *Key;
    void *Value;
};

typedef struct HashMap HashMap;
struct HashMap
{
    Bucket *BucketList;
    size_t Size;
    size_t KeySize;
    size_t ValueSize;
    int Entries;
};

HashMap *insert(HashMap *map, void *key, void *value)
{
    if (isOverLoad(map->Entries, map->Size, LOADFACTOR))
    {
        printf("\nMap is Overloaded.. Rehasing");
        map = reHash(map);
    }

    int bucketindex = hash(map->Size, key);
    printf("\nBucket index: %d",bucketindex);
    if (map->BucketList[bucketindex].Value != NULL)
    {
        printf("\nCollision! ");
        // printf("%s and %s", (char *)map->BucketList[bucketindex].Key, (char *)key);
    }
    else
    {
        printf("\nEntering value");
        map->BucketList[bucketindex].Key = malloc(map->KeySize);
        for (int i = 0; i < map->KeySize; i++)
        {
            *(((char *)map->BucketList[bucketindex].Key) + i) = *(((char *)key) + i);
        }

        map->BucketList[bucketindex].Value = malloc(map->ValueSize);
        
        for (int i = 0; i < map->ValueSize; i++)
        {
            *(((char *)map->BucketList[bucketindex].Value) + i) = *(((char *)value) + i);
        }
        map->Entries++;
    }
    return map;
}

【问题讨论】:

标签: c data-structures hashmap


【解决方案1】:

为了给你一个更好的答案,我还应该看看其他函数的代码,比如 reHash()。 但我可以给你两个建议:首先检查 reHash() 是否失败,因此 map == NULL;如果不是这种情况,您可以尝试使用valgrind 运行代码以更好地了解发生了什么。

【讨论】:

    猜你喜欢
    • 2017-05-06
    • 2019-05-17
    • 2010-12-04
    • 2012-01-23
    • 2011-10-01
    • 2013-02-12
    • 2013-08-23
    • 2019-03-26
    • 2010-11-16
    相关资源
    最近更新 更多