So I'm not getting load to work properly in PSET5. Any tips on what I'm doing wrong?
My method now:
- Scan char by char in file until EOF; increment index (global)
- Insert each item into the trie from the root (global) -> this also updates the pointer so the next character in the loop starts from that pointer
- Continuing will insert at the previous node recursively (I think).
- When you reach end of word, return the trie pointer to head and set index to 0;
Here's what that looks like FYI what most people call 'nodes' I've labled as 'trie' (struct with bool isWord and trie* children[27] (edit - mistyped here. it should be 27 because of the '\'' character slot):
trie* wordPtr = head;
for (int c = fgetc(fp); c != EOF; c = fgetc(fp))
{
if (isalpha(c) || (c == '\'' && index > 0))
{
wordPtr = insert(c, wordPtr);
index++;
}
else if (index > 0)
{
// update counter
num_words++;
endword(wordPtr);
wordPtr = head;
index = 0;
}
}
I've searched the forums and this 'insert' method seems to be pretty standard, but here's the code for it:
trie* insert(char c, trie* ptr)
{
if (c == '\'' && ptr->children[26] == 0)
{
ptr->children[26] = calloc(1, sizeof(trie));
return ptr->children[26];
}
else if (c == '\'' && ptr->children[26] != 0)
{
return ptr->children[26];
}
if (ptr->children[c -'a'] == 0)
{
ptr->children[c - 'a'] = calloc(1, sizeof(trie));
return ptr->children[c - 'a'];
}
else
{
return ptr->children[c - 'a'];
}
}
endword indeed just sets the ptr->isWord to true.
Any idea what I'm doing wrong? Can I update wordPtr in the way that I've done it (passing it to the a function and updating it on when that function returns)?
Thanks!