2013-03-19 27 views
1

我試圖從字典中的所有單詞實現fnv1a哈希函數(所以我可以稍後訪問它們)。如何在結構中的字符串上實現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; 
} 

這是如何我試圖讓哈希函數中稱爲負載()的一句話:

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 
+3

和問題是什麼? – 2013-03-19 12:07:58

+0

@TonyTheLion它不會編譯。對不起,我忘了注意,但你現在可以在我的問題底部看到錯誤:) – taevanbat 2013-03-19 12:09:19

+0

'ptr-> word'中的'word'類型是什麼? – 2013-03-19 12:10:07

回答

2

看來的ptr->word類型是一組charchar []。你不能增加一個數組,改變設計。

+0

所以如果我將它聲明爲char *,那麼這能解決問題嗎? – taevanbat 2013-03-19 12:12:46

+1

@teektaks如果它是一個指針,它可以遞增,但是你必須在'fscanf()'''字符串之前動態分配內存。但是,Thony Lion的解決方案確實很好。獲取一個指向數組的第一個元素的指針,它將起作用。 – 2013-03-19 12:14:32

+0

當然兄弟:) – taevanbat 2013-03-19 13:51:29

2

你可以簡單地解決您的問題,像這樣:

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

fnv1a(*ptr++, SEED); 
+0

你可以這樣寫:char * ptr = ptr-> word [0]而不是&ptr-> word [0]?我們是否需要和號運算符? – taevanbat 2013-03-23 06:17:21

+1

&是運營商的地址,是的,你需要它在這種情況下。 – 2013-03-23 11:07:10