【发布时间】:2015-08-05 23:06:26
【问题描述】:
我试图用字符串“(4+5)”调用函数buildExpressionTree 我尝试调试,发现树创建成功,但是当返回主目录时,“tr”为空并且包含垃圾。 为什么它无法返回树? 请帮忙,谢谢!
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;
}
这是“buildExpressionTree”函数:
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;
}
这是创建树的递归函数:
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;
}
}
【问题讨论】:
-
在您的主函数中,您将 tr 变量的地址传递给 buildExpressionTree 函数。在该函数中,您为 Tree 分配内存,但不将其传回。由于 tr 参数是一个指向 Tree 的指针,因此在为它分配内存时,只需更新函数中的本地 tr 变量即可。它对 main 函数的作用域没有影响。
-
Tree和TreeNode的定义是什么,Tree是结构体还是指针?
标签: c struct binary-tree dynamic-allocation