I need to start with the head node every cycle to add the new node in the right place. I think my current code makes the pointer for head and sptr equal so when I move one, the other one moves too. How do I move the pointer sptr to the beginning?
In debugger head->letter[1]
turns true when I save an "a" as a word as it should, but later turns back to false as soon as sptr = head;
runs. I think it has to do with the pointers.
typedef struct node
{
bool exist;
struct node* letter[28];
} trie;
trie *head = NULL;
int words = 0;
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
int i = 0;
FILE *infile = fopen(dictionary, "r");
if (infile == NULL)
{
printf("Could not open %s.\n", dictionary);
return 1;
}
// allocate memory
head = calloc(sizeof(trie), 1);
head->exist = false;
trie *sptr = head;
int cr;
// loop through file one character at a time
while ((cr = fgetc(infile)) != EOF)
{
// build a trie
// check if it's end of line
if (cr != 10)
{
i = tolower(cr) - 96;
// check for apostrophy
if (i < 0)
{
i = 0;
}
// check if the position exists
if (sptr->letter[i] == NULL)
{
sptr->letter[i] = malloc(sizeof(trie));
sptr->exist = false; // not the end of the word
}
sptr = sptr->letter[i];
}
else // indicate the end of a word that exists
{
sptr->exist = true;
sptr = head;// I think the problem might be here, I'm trying to move the pointer to the beginning.
words++;
}
}
return true;
}
Found the problem. It was in line sptr->exist = false, it should've read sptr->letter[i]->exist = false. The pointer was moving fine but I was changing the value of where the current pointer was, not the newly created node.