如何在结构中的字符串上实现fnv1a哈希函数?

时间:2013-03-19 12:04:14

标签: c pointers hashtable hash-function

我正在尝试在字典中的所有单词上实现fnv1a哈希函数(所以我可以稍后快速访问它们)。

这是fnv1a哈希函数:

int
fnv1a(unsigned char byte, uint32_t hash)
{
    hash = SEED;
    // SEED is a constant that I defined
    return ((byte ^ hash) * PRIME) % HASHTABLE_SIZE;
}

这就是我试图在一个名为load()的函数中获取单词的哈希值:

int hash = fnv1a((unsigned char)*(ptr->word)++, SEED);

这是完整的功能:

/ *  *将字典加载到内存中。如果成功则返回true,返回false。  * /

bool
load(const char *dictionary)
{    
    FILE* fp = fopen("words.txt", "r");

    // make new node to store the stuff in
    node *ptr = malloc(sizeof(node));
    ptr->next = NULL;

    // while it's not the end of the file
    while(!feof(fp))
    {
        // store the word in the ptr
        fscanf(fp, "%s", ptr->word);

        // get hash function for word
        int hash = fnv1a((unsigned char)*(ptr->word)++, SEED);

        // store word at hash value in hashtable

        // if there isn't a word there yet
        if (hashtable[hash]->next == NULL) 
            hashtable[hash]->next = ptr;  

    // else go to the end of the list and add the word

    // haven't done this part yet

    if (hashtable == NULL)
    {
        printf("Didn't work out, bud");
        return false;
    }   

    else 
        return true;
}

编译此代码时我遇到的错误(指向我试图散列单词的行):

dictionary.c:70:53: error: lvalue required as increment operand

2 个答案:

答案 0 :(得分:2)

似乎ptr->word的类型是charchar []的数组。你无法增加数组,改变设计。

答案 1 :(得分:2)

你可以简单地解决你的问题:

char* ptr = &ptr->word[0];

fnv1a(*ptr++, SEED);