1

Im trying to call the function buildExpressionTree with the string "(4+5)" I tried to debug and found out that the tree is created successfully but when returned back to main, "tr" is empty and contains garbage. why does it fail to return the Tree? please help, thank you!

int main(){

char str[SIZE];
Tree tr;
double res;
BOOL expressionOK;
printf("Please enter the expression: ");
gets(str);

expressionOK = buildExpressionTree(str, &tr);

freeTree(tr);

return 0;

}

this is "buildExpressionTree" Function:

BOOL buildExpressionTree(char * str, Tree * tr){

BOOL valid = isvalidString(str);

if (valid){

    tr = (Tree *)malloc(sizeof(Tree));
    tr->root = buildTree(str, strlen(str));
}

else{
    tr = NULL;
}

return valid;

}

and this is the recursive function creating the tree:

TreeNode * buildTree(char * str, int strLength){

int mainOpPlace;
TreeNode * resNode;

//if empty tree
if (strLength < 0){
    return NULL;
}

else{

    //find the main operator of the current string
    mainOpPlace = findMainOperator(str, strLength);

    //creating the tree Node
    resNode = (TreeNode *)malloc(sizeof(TreeNode));

    resNode->data = str[mainOpPlace];
    resNode->left = (buildTree(str + 1, mainOpPlace - 1));
    resNode->right = (buildTree(str + mainOpPlace + 1, (strLength - mainOpPlace - 2)));

    return resNode;
}

}

Dor Amar
  • 171
  • 1
  • 7
  • In your main function you pass the address of the tr variable to the buildExpressionTree function. Within that function you allocate memory for the Tree but you do not pass it back. Since the tr parameter is a pointer to a Tree, when you allocate memory for it, you just update the local tr variable in the function. It has no effect on the main function's scope. – OrenD May 24 '15 at 09:27
  • what's the defination of `Tree` and `TreeNode`, is `Tree` a struct or pointer ? – simon_xia May 24 '15 at 09:28

1 Answers1

0

You need buildExpressionTree() to return the address of the tree memory allocated by malloc. You could do this by typing the function as Tree*, moving the return of the bool parameter into the parameter list

Tree *buildExpressionTree(char * str, BOOL * AddressOfExpressionOK ) { ..

or you could return it inside the parameter list, placing the value of the tree pointer at an adress supplied by the caller, as a pointer to pointer to Tree,

BOOL buildExpressionTree(char * str, Tree **ptr){ ..

but I think the other approach is easier to read.

Spalteer
  • 454
  • 4
  • 11