Unable to store string's into my Binary Search Tree?
This is my first time really resorting to asking for help online, I have been able to handle most of my programming projects by myself until now.
I am required to make a binary search tree that will read in a dictionary of words (from a text file I designate).
I am having some errors however in actually storing the words into my BST.
I get error C2106 = left operand must be l-value for the line "
Code:
p->data = malloc(strlen(value) + 1);
and
Code:
strcpy(p->data, value);
will cause my program to crash upon reaching this point.
Code:
/* Structure Definition
struct treeNode {
char data[20];
struct treeNode *left;
struct treeNode *right;
};
*/
// The following is the main part of the function that reads in each word and attempts to store it to the BST.
if ((filePtr = fopen (fileName, "r"))== NULL)
printf ("Sorry the file could not be opened. \n"); // Attempts to open the file.
else
{
while (!feof (filePtr))
{
fgets(buffer, 20, filePtr);
printf ("%s", buffer);
treeNode_insert(root, buffer);
}
}
// This last bit is the actual insert, but this is where I am having the errors.
struct treeNode *treeNode_insert(struct treeNode *p, char value) {
struct treeNode *tmp_one = NULL;
struct treeNode *tmp_two = NULL;
int resultforTemp1;
int resultforTemp2;
if(p == NULL) {
/* insert [new] treeNode as root node */
p = (struct treeNode *)malloc(sizeof(struct treeNode));
p->data = malloc(strlen(value) + 1); // Throws errors.
strcpy(p->data, value); // Throws errors.
p->left = p->right = NULL;
} else {
tmp_one = p;
/* Traverse the tree to get a pointer to the specific treeNode */
/* The child of this treeNode will be the [new] treeNode */
while(tmp_one != NULL)
{
tmp_two = tmp_one;
resultforTemp1 = strcmp (tmp_one->data, value);
if(resultforTemp1 > 0)
tmp_one = tmp_one->left;
else
tmp_one = tmp_one->right;
}
resultforTemp2 = strcmp(tmp_two->data, value);
if(resultforTemp2 > 0)
{
/* insert [new] treeNode as left child */
tmp_two->left = (struct treeNode *)malloc(sizeof(struct treeNode));
tmp_two = tmp_two->left;
strcpy(tmp_two->data, value);
// tmp_two->data = value;
tmp_two->left = tmp_two->right = NULL;
} else {
/* insert [new] treeNode as left child */
tmp_two->right = (struct treeNode *)malloc(sizeof(struct treeNode));
tmp_two = tmp_two->right;
strcpy(tmp_two->data, value);
// tmp_two->data = value;
tmp_two->left = tmp_two->right = NULL;
}
}
return(p);
}