2015-05-24 24 views
1

我試圖調用函數buildExpressionTree與字符串「(4 + 5)」 我試圖調試,發現樹已成功創建,但當返回到主,「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; 
} 

}

+0

在您的主函數中,您將tr變量的地址傳遞給buildExpressionTree函數。在那個函數中,你爲樹分配內存,但是你不會傳回它。由於tr參數是一個指向Tree的指針,因此當爲它分配內存時,只需更新函數中的本地tr變量即可。它對主函數的作用域沒有影響。 – OrenD

+0

'Tree'和'TreeNode'的定義是什麼,Tree是一個結構體還是指針? –

回答

0

您需要buildExpressionTree()來返回由malloc分配的樹存儲器的地址。你可以通過輸入功能樹*,移動布爾參數返回到參數列表

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

,或者你可以返回它的參數列表中,將樹指針的值在ADRESS做到這一點作爲指向樹的指針提供,

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

但我認爲另一種方法更容易閱讀。