So I'm doing pset5, speller.
I'm storing the words in the dictionary in a trie, whose root is a pointer to a node, called root
.
root
is a global variable first initialized to NULL.
root
is first used in the function load
, which allocates memory to root
.
Now, when the next function that uses root
is called, the value of root
is shown to be 0x0.
I can't fathom why this is happening.
Also, I apologize if a similar question has been asked in the past. I have searched for quite a while with no avail, but that might have been due to some ignorance or misunderstanding on my part.
Extra info I'm not sure whether or not you need:
All my work is in the file
dictionary.c
, which defines functions that are called byspeller.c
. Only the functions in dictionary.c useroot
.Here is how I define a node:
typedef struct node { bool is_word; //set to true if end of valid word struct node* children[27];//This is an array, each element of which is pointer to a node. } node;
root
is then initialized asnode* root = NULL;
(All code mentioned above is at the top of
dictionary.c
, right after all the#include
stuff.)Here is what
load
looks like:bool load(const char *dictionary) { FILE* fp = fopen(dictionary, "r"); node* root = malloc(sizeof(node)); /**following code is probably irrelevant, seeing it only *mentions root at all when it assigns node* now the value of root. *but here it is just in case. */ if(dictionary==NULL) { return false; } char word[LENGTH+1]={'\0'}; while(fscanf(fp, "%s", word)!=EOF)//get words until EOF. { //we want to store a pointer to where we are now. node* now = root; int x; for(int i = 0; word[i]!='\0'; i++)//idk if fscanf actually puts the '\0' in word[] { if(isalpha(word[i])) { x = tolower(word[i]) - 'a'; } else if(word[i]=='\'') { x = 26;//change this to non magic no. whatever. ugh. } if (now->children[x]==NULL) { now->children[x] = malloc(sizeof(node)); if(now->children[x]==NULL) { return false; } } now = now->children[x]; }//close for loop now->is_word = true;//to mark valid word. s++;//global var, counter for size of dictionary. }//close while loop return true; }
To check for any accidental reassignments that might have occurred during
load
, I hadload
print me the addressroot
pointed to in every loop inside, and in the last line ofload
. The value was always the same.