I am trying to implement the check function of Speller in CS50. The code below may or may not work. But the thing that gets me is that I don't understand the bit :
if strcasecmp(cursor-> word, tword) !=0)
cursor= cursor-> next;
Doesn't this mean it is comparing against itself? tword is derived from word. So surely it is comparing against itself??
// Implements a dictionary's functionality
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include "dictionary.h"
// Represents number of buckets in a hash table
#define N 26
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
// declare words to count in dictionary
int dictionarysize = 0;
// Represents a hash table
node *hashtable[N];
// Hashes word to a number between 0 and 25, inclusive, based on its first letter
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)
{
// TODO
node *new_node = malloc(sizeof(node));
if (new_node == NULL)
{
unload ();
return false;
}
else
{
strcpy (new_node -> word, word);
}
//implement hash function to get an index
int index = hash(word);
// if corresponding index in hashtable is empty, assign it to the new node
// else append new node to the start of the linked list
if (hashtable[index]==NULL)
{
hashtable[index] = new_node;
}
else
{
new_node->next = hashtable [index];
hashtable [index] = new_node;
}
dictionarysize++;
}
// Close dictionary
fclose(file);
// Indicate success
return true;
}
// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
// TODO
if (dictionarysize >= 1)
{
return dictionarysize;
}
else
{
return 0;
}
}
// Returns true if word is in dictionary else false
bool check(const char *word)
{
// TODO
{
//find out length of word
int lengthword = strlen(word);
//create an array to store word
char tword[lengthword + 1];
// make it lowercase before hashing
for (int i = 0; i < lengthword; i++)
{
tword[i] = tolower(word[i]);
}
tword[lengthword] = '\0';
// hash it and find out which bucket it belongs in
int bucket = hash(tword);
node *cursor = hashtable [bucket];
// compare words
while (cursor != NULL)
{
if (strcasecmp(cursor->word, tword) != 0)
cursor = cursor->next;
else
return true;
}
return false;
}
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
// TODO
return false;
}