Hi, i am having trouble understanding the implementation of a hash table. I've been on quite a few links off google and still can't get my head round it!
My project needs to store all the words from a text file in a hash table (using linked lists to deal with collisions), when an identical word is inserted it increments the frequency value of the list element instead of making a new entry in the linked list.
First off, here is what i have:
structs to deal with table and lists.
called somewhere in main withCode:typedef struct HL { char string[20] ; int frequency ; //to deal with identical words inserted struct HL *next ; } Hash_list ; typedef struct HT { int size; Hash_list **table; } Hash_table;:Code:Hash_table table = createTable() ;
Then code for inserting word (in a loop):Code:Hash_table *createTable( void ) { Hash_table *hashTable = calloc(1 , sizeof(Hash_table)) ; hashTable->size = 8 ; hashTable->table = (Hash_list**)malloc(hashTable->size * sizeof(Hash_list)) ; int i ; for(i = 0 ; i < hashTable->size ; i++) hashTable->table[i] = (Hash_list*)malloc(sizeof(Hash_list)) ; return hashTable ; }
Code:fscanf(f, "%s" , word) ; format(word) ; //removes special characters and capitalises every character table = addTableElement(table , word) ;Code:/* Add new element to hash table */ Hash_table *addTableElement(Hash_table *old , char *elem){ int h = hash(elem) ; //get hash key of string (currently returns 0 for testing) old->table[h] = addHashElement(old->table[h] , elem); //add it to correct list return old ; //return edited hash table }Code:/* Add new element to Hash_list */ Hash_list *addHashElement(Hash_list *old , char *elem){ if(old == NULL){ return makeHashList(elem , NULL) ; //if no entries in this list yet, create using makeHashList }else{ Hash_list *new ; for(new = old ; new->next != NULL ; new = new->next) { if(strcmp(new->string , elem) == 0){//if it finds the string already in hash list new->frequency++ ; //add one to the frequency value while(new->next != NULL)//continue iterating through list new = new->next ; return old ; //then return the list } } new->next = makeHashList(elem , NULL) ;//if the string is not in the list, make a new entry in the list return old ;//then return it } }Ok, sorry about all that, i've tried to give you the bare minimum code! At the moment the program crashes at the line:Code:/* Create element in Hash_list */ Hash_list *makeHashList (char *string , Hash_list *next){ Hash_list *new = calloc(1 , sizeof(Hash_list)) ; strncpy(new->string , string , 20) ; new->next = next ; new->frequency = 1 ; return new ; }
old->table[h] = addHashElement(old->table[h] , elem);
in function addTableElement(Hash_table *old , char *elem).
I think it is because of the way i constructed the hash table in function createTable() , but i'm not sure!
please, if anyone can help that would be great!
-Ed



LinkBack URL
About LinkBacks




What's wrong with