I'm trying to use tries with pset5. Based on some error checking, it seems the newNodes I'm creating and the links between them are not carrying over from one word to the next. In other words, if the dictionary loads the word "cat", and then "caterpillar", it seems to be creating new nodes for the "a" and the "t" all over again. I can't figure out why.
Here is my code. Thanks in advance for any advice you can offer. Also, I know I haven't accounted for apostrophes yet. I want to get the code working and then I'll integrate apostrophes.
/**
* dictionary.c
*
* Computer Science 50
* Problem Set 5
*
* Implements a dictionary's functionality.
*/
#include <cs50.h>
#include <ctype.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "dictionary.h"
/* in dictionary.h
*
*
typedef struct node
{
bool is_word;
struct node* next[26];
}
node;
*/
// hashed number
int h_num;
node* root = NULL;
/**
* Loads dictionary into memory. Returns true if successful else false.
*/
bool load(const char* dictionary)
{
// open dictionary "d" for reading
FILE* d = fopen(dictionary, "r");
// Error checking
if (d == NULL)
{
printf("Could not load dictionary.\n");
return false;
}
root = malloc(sizeof(node));
for (int j = 0; j < 26; j++)
{
node* child = calloc(1, sizeof(node));
root->next[j] = child;
}
while (!feof(d))
{
// array to hold the words of the text file
char str[LENGTH + 1];
// read the word
fscanf(d, "%s", str);
// keep track of strlen so you know when to change is_word to true
int wordlen = strlen(str);
// this int will iterate through the chars in the str
int i = 0;
// number to determine alphabetic index of pointer
h_num = str[i] - 'a';
// for moving from node to node
node* trav = root;
// if node has already been created, jump to furthest down node already created
while (trav->next[h_num] != NULL)
{
// using this formula again so it can reset each time the node jumps
int h_num = str[i] - 'a';
// trav node jumps to next node
trav = trav->next[h_num];
if (i + 1 == wordlen)
{
trav->is_word = true;
}
i++;
printf("preexisting node\n"); // error checking
}
// create new nodes for remainder of word
while (i < wordlen)
{
int h_num = str[i] - 'a';
node* newNode = malloc(sizeof(node));
trav->next[h_num] = newNode;
trav = newNode;
printf("created node\n"); // error checking
if (i + 1 == wordlen)
{
trav->is_word = true;
printf("word\n"); // error checking
}
i++;
}
total++;
}
fclose(d);
return true;
}