So currently I'm working on speller and I suspect that there's a mistake(s) in load(). When I run my code it does load without an error message and correctly checks some words successfully and fails to check some words. I've been looking at my code for a couple of days now and I fail to see where my code doesn't make sense.
//global variables
int counter = 0;
sllnode *headp[10000];
sllnode *hashtable[10000];
int key;
bool load(const char *dictionary)
{
// TODO
//opens dictionary
FILE *file = fopen(dictionary, "r");
if(file == NULL)
{
printf("Failed to open file.\n");
return false;
}
//starts to load
else
{
//char array
char word[LENGTH + 1];
while(fscanf(file, "%s", word) != EOF)
{
//hash word
key = hash_word(word);
//checks if bucket is empty
if(hashtable[key] == NULL)
{
hashtable[key] = create(word);
headp[key] = hashtable[key];
counter++;
}
//if bucket is not empty
else if(hashtable[key] != NULL)
{
hashtable[key] = insert(&hashtable[key], word);
headp[key] = hashtable[key];
counter++;
}
//error
else
{
fclose(file);
return false;
}
}
fclose(file);
//success
return true;
}
fclose(file);
return false;
}
//creates list
sllnode* create(char word[])
{
sllnode *node = malloc((sizeof(sllnode)));
if(node == NULL)
{
unload();
printf("Memory error in creating list\n");
return false;
}
strcpy(node->string, word);
node->next = NULL;
return node;
}
//insert node
sllnode* insert(sllnode *head[], char word[])
{
sllnode *node = malloc((sizeof(sllnode)));
if(node == NULL)
{
unload();
printf("Memory error in creating list\n");
return false;
}
strcpy(node->string, word);
node->next = headp[key];
return node;
}
//hash function
unsigned int hash_word(const char* word)
{
unsigned long hash = 5381;
for (const char* ptr = word; *ptr != '\0'; ptr++)
{
hash = ((hash << 5) + hash) + tolower(*ptr);
}
return hash % 10000;
}
//hash fuction is taken from github.com/hathix/cs50-section/blob/master/code/7/sample-hash-functions/good-hash-function.c
I've included all the fuctions for load() to work