Hello all,
Basically what I'm trying to do here is read in an integer from the file which contains the number of words in the file and then iteratively read the words themselves in. The insert function is recursive in nature and is meant to insert the words into a binary search tree. The problem that I'm having is after the first word has been read in, the insert function is called, and the tree_node object is no longer null, everytime I scan in a new word from the file, the word object of tree_node is automatically updated with that word before even calling the insert function. Consequently, when the insert function is called, it matches none of the criteria except else. My guess is that when p->word is assigned to tree_word in the insert function, it stores the address of tree_word and is therefore always matches in tree_word but I am by no means sure that is correct. The code is as follows:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct treenode
{
char *word;
struct treenode *left;
struct treenode *right;
} tree;
void make_tree(FILE *filepointer);
tree *insert(char *tree_word, tree *p);
int main()
{
FILE *fp;
char filename[16];
printf("Please enter file name: ");
printf("\n>");
scanf("%s", filename);
fp = fopen(filename, "r");
make_tree(fp);
return 0;
}
void make_tree(FILE *filepointer)
{
tree *tree_node = NULL;
int num_words, cnt;
char tree_word[16];
fscanf(filepointer, "%d", &num_words);
for(cnt = 0; cnt < num_words; cnt++)
{
fscanf(filepointer, "%s", &tree_word);
tree_node = insert(tree_word, tree_node);
}
}
tree *insert(char *tree_word, tree *p)
{
if(p == NULL)
{
p = (tree *)malloc(sizeof(tree));
p->word = tree_word;
p->left = NULL;
p->right = NULL;
}
else if(strcmp(p->word,tree_word) < 0)
{
p->left = insert(tree_word, p->left);
}
else if(strcmp(p->word,tree_word) > 0)
{
p->right = insert(tree_word, p->right);
}
else
;
return p;
}
Any help on this would be greatly appreciated.
Thanks,
Jonathan