After debugging for a long long time, it turned out that my hashtable must have some problem. Therefore, to find out where the problem is, I put this line of code after I insert a word in the hashtable. I suppose that this will print out just the first word in the first linked list. However, after I run my code, all the words in the dictionary are printed! Moreover, only words started with 'z' are fully printed, while other words, started with 'a' to 'y', are all printed "null" (just like the pictures below)
By the way, whenever I run my code, the result always stops at MISSPELLED WORDS.
Please help me figure this out! Thanks a lot!
printf("%s\n", hashtable[0]);
// Represents number of buckets in a hash table
#define N 26
// Represents a hash table
node *hashtable[N];
// Initializes sizeCounter
int sizeCounter = 0;
unsigned int hash(const char *word)
{
return tolower(word[0]) - 'a';
}
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
// Initialize hash table
for (int i = 0; i < N; i++)
{
hashtable[i] = NULL;
}
// Open dictionary
FILE *file = fopen(dictionary, "r");
if (file == NULL)
{
unload();
return false;
}
// Buffer for a word
char word[LENGTH + 1];
// Insert words into hash table
while (fscanf(file, "%s", word) != EOF)
{
// Malloc a node* for each new word
node *new_node = malloc(sizeof(node));
if (new_node == NULL)
{
unload();
return false;
}
// If it succeeds, copy the word into the node
strcpy(new_node->word, word);
// Insert into a linked list
int hashCode = hash(word);
printf("%i\n", hashCode);
if (hashtable[hashCode] == NULL)
{
hashtable[hashCode] = new_node;
new_node->next = NULL;
}
else
{
new_node->next = hashtable[hashCode];
hashtable[hashCode] = new_node;
}
printf("%s\n", hashtable[0]);
// Add 1 to count_size each time after inserting a word into a linked list
sizeCounter++;
// Free memory
free(new_node);
}
// Close dictionary
fclose(file);
// Indicate success
return true;
}
// Returns true if word is in dictionary else false
bool check(const char *word)
{
int l = strlen(word);
char *tempWord = malloc(sizeof(char) * (l + 1));
for(int i = 0; i < l; i++)
{
tempWord[i] = tolower(word[i]);
}
tempWord[l + 1] = '\0';
node *cursor = hashtable[hash(tempWord)];
// Check whether word is in dictionary
while (cursor != NULL)
{
if (strcmp(tempWord, cursor->word) == 0)
{
free(tempWord);
return true;
}
else
{
cursor = cursor->next;
}
}
free(tempWord);
// If word not in dictionary
return false;
}
printf("%s\n", hashtable[0]);
would cause a compiler failure. Isn't hashtable an array of pointers? Can you please add all the relevant declarations, and the hash and check functions to the question?