2014-09-02 65 views
-1

我試圖實現鏈式哈希表中C.這是一個項目從一門課程,因此不會是完美的,但我不能讓它上班。哈希表的實現 - 裏面只有垃圾值

在我添加新值的哈希表的一切方法似乎不錯,但後來當我試圖找到在哈希表中某些價值似乎沒有什麼內部(或一些垃圾值)。我認爲散列函數工作正常,所以我不會發布它。下面是相關代碼:

// typedef a node for the linked list 
typedef struct node 
{ 
    char* value; 
    struct node* next; 
} 
node; 

// global variables 
node* head = NULL; 
node* lists[145000]; 

// this method inserts a new value into the hash table 
bool insert_word(char* value, int index) 
{ 
    // inserting at the beginning of the list 
    node* new_node = malloc(sizeof(node)); 
    new_node->value = value; 

    if (head == NULL) 
    { 
     head = new_node; 
    } 
    else 
    { 
     new_node->next = head; 
     head = new_node; 
    } 

    lists[index] = head; 

    return true; 
} 

// this method should check if the searched word 
// is present in the hash table 
bool check(const char* word) 
{ 
    int index = hash(word); 

    node* curr_node = lists[index]; 

    while (curr_node != NULL) 
    { 
     if (strcmp(curr_node->value, word) == 0) // this never happens 
     { 
      return true; 
     } 
     curr_node = curr_node->next; 
    } 

    return false; 
} 

,因爲我一直是這樣掙扎了兩天,我希望得到任何幫助......謝謝:)

+0

你應該與所有警告和調試信息(例如'GCC -Wall -g')編譯,你應該**使用調試器**(例如'gdb')。你真的無法避免使用調試器 – 2014-09-02 10:07:38

+1

你不在上面的代碼塊中定義'node'。 – 2014-09-02 10:09:00

+1

如何調用'bool insert_word(char * value,int index){}'? (在分配給node-> value之前,可能需要strdup()參數) – joop 2014-09-02 10:10:47

回答

1

您在

node* new_node = malloc(sizeof(node)); 
new_node->value = value; 
分配一個新的節點

但你不是測試的malloc失敗,你是不是總是設置new_nodenext場(讓現場可能含有垃圾時headNULL)。

試着這麼做

node* new_node = malloc(sizeof(node)); 
if (!new_node) {perror("malloc node"); exit(EXIT_FAILURE); }; 
new_node->value = value; // probably needs:: strdup (value) 
new_node->next = NULL; 

最重要的是,所有的警告和調試信息編譯(例如用gcc -Wall -g如果使用GCC),並學會如何使用調試器(例如gdb)。

使用也很喜歡valgrind內存泄漏檢測儀......

最後,我們不知道怎麼insert_node叫什麼名字?我猜(例如joop評論)您可能想要複製字符串,例如使用new_node->value = strdup(value);

+0

謝謝大家。使用new_node-> value = strdup(value)解決了這個問題。 – user2651221 2014-09-02 13:18:17