This is my program:
// Implements a dictionary's functionality
#include <ctype.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <strings.h>
#include "dictionary.h"
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
// TODO: Choose number of buckets in hash table
const unsigned int N = 26;
int count_word = 0;
// Hash table
node *table[N];
// Returns true if word is in dictionary, else false
bool check(const char *word)
{
int index=hash(word);
node *cursor = table[index];
while (cursor != NULL)
{
if (strcasecmp(word,cursor->word) == 0)
{
return true;
}
cursor= cursor->next;
}
return false;
}
// Hashes word to a number
unsigned int hash(const char *word)
{ int c =0;
for(int i = 0; i<strlen(word); i++)
{
c+=tolower(word[i]);
}
// TODO: Improve this hash function
return (c % N);
}
// Loads dictionary into memory, returning true if successful, else false
bool load(const char *dictionary)
{
FILE *file = fopen(dictionary,"r");
if (file == NULL)
{
return false;
}
char word[LENGTH +1];
while(fscanf(file,"%s",word) != EOF)
{
node *n= malloc(sizeof(node));
if (n == NULL)
{
fclose(file);
return false;
}
strcpy(n->word ,word);
int index = hash(n->word);
n->next = table[index];
table[index]=n;
count_word++;
}
// TODO
fclose(file);
return true;
// TODO
return false;
}
// Returns number of words in dictionary if loaded, else 0 if not yet loaded
unsigned int size(void)
{
// TODO : TO return thr number of words
return count_word;
}
// Unloads dictionary from memory, returning true if successful, else false
bool unload(void)
{
for(int i=0 ;i<26;i++)
{
node *tmp = table[i];
while( tmp != NULL)
{
node *cursor = tmp;
cursor = cursor->next;
free(tmp);
tmp = cursor;
}
if (tmp == NULL)
{
return true;
}
}
// TODO
return false;
}
This is what the CS50 tool is showing:
:) dictionary.c exists
:) speller compiles
:) handles most basic words properly
:) handles min length (1-char) words
:) handles max length (45-char) words
:) handles words with apostrophes properly
:) spell-checking is case-insensitive
:) handles substrings properly
:( program is free of memory errors
valgrind tests failed; see log for more information.