C编程 - 哈希表实现 - 双指针

时间:2016-09-20 01:20:22

标签: c pointers memory hashtable

有人可以解释为什么我们会在以下double pointers中对**keys**values使用struct

typedef struct {
    int size;
    void **keys;
    void **values;
} hash_t;

是不是因为*h在这种情况下指向hash_t结构本身的指针?

hash_t *h = calloc(1, sizeof(hash_t));

h->keys = calloc(size, sizeof(void *));
h->values = calloc(size, sizeof(void *));

感谢。

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

typedef struct {
    int size;
    void **keys;
    void **values;
} hash_t;

hash_t *hash_new(int size) 
{
    hash_t *h = calloc(1, sizeof(hash_t));

    h->keys = calloc(size, sizeof(void *));
    h->values = calloc(size, sizeof(void *));
    h->size = size;

    return h;
}

int hash_index(hash_t *h, void *key)
{
    int i = (int) key % h->size;

    while(h->keys[i] && h->keys[i] != key) {
        i = (i + 1) % h->size;
    }

    return i;
}

void hash_insert(hash_t *h, void *key, void *value)
{
    int i = hash_index(h, key);
    h->keys[i] = key;
    h->values[i] = value;
}

void *hash_lookup(hash_t *h, void *key)
{
    int i = hash_index(h, key);
    return h->values[i];
}

int main()
{
    hash_t *h = hash_new(15);

    hash_insert(h, "Key", "Value");

    printf("%s\n", hash_lookup(h, "Key"));
}

0 个答案:

没有答案