I am having problems with pset 5. Honestly so far I have never had such a huge problems with a pset. I watched every video, read many questions and answers on stack exchange and wrote some code, which compiles, but it doesn't work. I was trying to find the problem, but I'm afraid I still don't understand everything in this pset, so I'm looking for any help I could get. I'm giving you my whole code in edit and hoping for your comments.
#include <stdbool.h>
#include "dictionary.h"
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int counter = 0;
// trie struct
typedef struct node
{
bool is_word;
struct node* children[27];
}
node;
node* root;
/**
* Returns true if word is in dictionary else false.
*/
bool check(const char* word)
{
// trie
node* root = malloc(sizeof(node));
node* csr = root;
int i = 0;
int idx = tolower(word[i]) - 'a';
while (word[i] != '\0')
{
if (isalpha(word[i])) // if char is alphabetical
{
if (csr->children[idx] != NULL)
{
csr = csr->children[idx];
i++;
}
else
{
return false;
}
}
else if (word[i] == '\'') // if char is apostrophe
{
if (csr->children[idx] != NULL)
{
csr = csr->children[idx];
i++;
}
else
{
return false;
}
}
else
return false;
}
if (csr->is_word == true)
return true;
else
return false;
}
/**
* Loads dictionary into memory. Returns true if successful else false.
*/
bool load(const char* dictionary)
{
// open file
FILE* dic = fopen("dictionary", "r");
if (dic == NULL)
{
printf("Could not open dictionary\n");
return 1;
}
// trie
node* root = malloc(sizeof(node));
node* csr = NULL;
int c = fgetc(dic); // reads each char
int index = tolower(c) - 'a';
while (c != EOF)
{
csr = root;
do
{
// checks if it is alphabetical char
if (isalpha(c))
{
if (csr->children[index] == NULL) // if lack of that char
{
csr->children[index] = malloc(sizeof(node));
}
csr = csr->children[index];
}
else if (c == '\'') // if apostrophe
{
if (csr->children[26] == NULL)
{
csr->children[26] = malloc(sizeof(node));
}
csr = csr->children[26];
}
c = fgetc(dic);
}
while (c != '\n');
csr->is_word = true;
counter++;
c = fgetc(dic);
}
return true;
}
/**
* Returns number of words in dictionary if loaded else 0 if not yet loaded.
*/
unsigned int size(void)
{
if (counter > 0)
{
return counter;
}
else
return 0;
}
/**
* Unloads dictionary from memory. Returns true if successful else false.
*/
void ftrie (node* csr)
{
// children
for (int i = 0; i < 27; i++)
{
if (csr->children[i] != NULL)
{
csr = csr->children[i];
ftrie(csr);
}
else if (csr->children[i] == NULL)
{
free(csr->children[i]);
}
}
}
bool unload(void)
{
node* csr = NULL;
csr = root;
ftrie(csr);
return true;
}