The problem is not just with your insert. You really defined your hash table wrong.
Here's some code I think should work.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define HASHSIZE 997
#define FILENAME "myfile.txt"
typedef struct Node {
char Value[128];
struct Node *next;
} listNode;
listNode* HashTable[HASHSIZE];
int hash(char *key);
int hash_insert(char *key);
char* hash_find(char* key);
void hash_destroy();
int main()
{
FILE *file;
int count;
char word[15] = {'\0'};
int quit = 0;
char* p;
for (count = 0; count < HASHSIZE ; count++) {
HashTable[count] = NULL;
}
if ((file = fopen(FILENAME, "r")) == NULL) {
fprintf(stderr, "File could not open!!\n");
return(EXIT_FAILURE);
}
while(fscanf(file,"%s",word) == 1) {
hash_insert(word);
}
fclose(file);
while(!quit) {
printf("Enter a word (Q to quit): ");
fflush(stdout);
if (fgets(word, sizeof word, stdin) != NULL) {
p = strchr(word, '\n');
if (p != NULL)
*p = '\0';
if ((word[0] == 'q' || word[0] == 'Q') && word[1] == '\0')
quit = 1;
else {
if (hash_find(word) != NULL)
printf("Word in dictionary\n");
else
printf("Word not in dictionary\n");
}
}
}
hash_destroy();
return 0;
}
int hash(char *key)
{
unsigned int hash_val = 0;
while(*key != '\0')
hash_val += *(key++);
return(hash_val % HASHSIZE);
}
char* hash_find(char* key)
{
listNode* curr;
int pos;
pos = hash(key);
curr = HashTable[pos];
while(curr != NULL) {
if (!strcmp(curr->Value, key))
return key;
curr = curr->next;
}
return NULL;
}
int hash_insert (char *key)
{
listNode *newptr, *curr;
int pos;
pos = hash(key);
/* make sure it's not already in the hash table */
curr = HashTable[pos];
while(curr != NULL) {
if (!strcmp(curr->Value, key))
return 1;
curr = curr->next;
}
newptr = malloc(sizeof(listNode));
if (newptr == NULL){
printf("Not Enough Memory!\n");
exit(EXIT_SUCCESS);
}
strcpy(newptr->Value, key);
newptr->next = NULL;
if (HashTable[pos] == NULL)
HashTable[pos] = newptr;
else {
listNode* headptr = HashTable[pos];
HashTable[pos] = newptr;
HashTable[pos]->next = headptr;
}
return 1;
}
void hash_destroy()
{
int i;
listNode* curr;
listNode* tmp;
for (i = 0; i < HASHSIZE; i++) {
curr = HashTable[i];
while(curr != NULL) {
tmp = curr->next;
free(curr);
curr = tmp;
}
}
}