首页 文章

C哈希表Set / Get void *唯一的内存地址

提问于
浏览
-1

Hashtable使用表中每个条目的链接列表 . Hashcode算法生成索引 . 哈希码算法的输入是键/值对的键 . 哈希码算法采用char *输入并输出整数索引 . Hashtable Get / Set方法可以通过使用void *和数据大小来获取任何类型的输入 . 为了生成一个几乎唯一的索引,输入字符串必须是唯一的,但Set / Get函数需要相互对应,这样如果在Set函数中键是“foobar”,那么稍后调用Get使用“foobar”映射到相同的哈希表索引 .

问题是输入是void *并且生成索引需要一个唯一的字符串然后我唯一能想到的是链接列表中将要存储的节点中键的唯一内存地址的字符串表示在哈希表中的那个索引处 .

设置功能(部分示例代码)

struct Node* node_to_set = Node_Create(entry->key, entry->data, entry->keysize, entry->datasize);
void* key = Node_Get_Key(node_to_set);
char string_key[256] = {'\0'};
int bytes = sprintf(string_key, "%p", key);
int index = Hashtable_HashCode(hashtable->size, string_key);

获取函数(该唯一字符串丢失给外部调用者)

//do not know what the memory address is because its in the table
//searching for it would defeat the purpose of a constant time lookup

有没有其他方法可以使用void *?

1 回答

  • 0

    而不是使用内存地址的字符串表示来传递给哈希函数 . 我使用了dereferenced值,这是唯一的,因为它是一个键 . 我通过将void *转换为unsigned char *来取消引用它,然后将其传递给hash函数 .

    int index = Hashtable_HashCode(hashtable->size, (unsigned char*)entry->key);
    
    unsigned long Hashtable_HashCode(unsigned int size, unsigned char *str) {
            if(str != NULL) {
                    unsigned long hash = 5381;
                    unsigned int c = 0;
                    while(c = *str++) {
                            hash = ((hash << 5) + hash) + c;
                    }
                    hash = hash % size;
                    hash = (hash < 0) ? hash * -1 : hash;
                    return hash;
            }
            return -1;
    }
    

相关问题