2017-04-03 22 views
-1
int find(char* a, trie_node* node, int result){//need to make sure a is not NULL at beginning 
    int i,temp; 
    if ((a != NULL && a[0] !='\n') && node->children[a[0] - 97] == NULL) 
    { 
     result = 0;//not found any children satisfied the requirement 
    } 
    else if ((a != NULL && a[0] !='\n') && node->children[a[0] - 97] != NULL){ 
     temp = a[0]; 
     a++; 
     find(a, node->children[temp - 97], result); 
    } else{//a == NULL, which means end of the find procedure, just return the num_children 
     result = node->num_children; //most inner one 
    } 
    return result; 
} 

我試圖從這個函數返回結果。由於它是一個嚴格的c程序,我需要在函數結束時返回聲明。C:從遞歸調用返回一個值

我在gdb中跟蹤它後,最內部的函數調用返回正確的數字結果。但是,在返回外部函數期間結果的值會丟失。因此,這個函數將返回0,這是錯誤的。我怎麼能夠回報並保持最內在的價值?

+0

爲什麼你的函數有'result'參數?它的價值從未被使用過。 – melpomene

+0

@melpomene最初,我沒有在添加功能。然而,因爲我需要返回函數結尾的結果,我認爲最好有一個參數作爲一個全局變量,它可以存儲來自內部函數的值。這就是爲什麼我添加結果。 –

+0

參數是局部變量。 「*作爲全局變量的參數*」沒有意義。 – melpomene

回答

2

你只需要添加return語句。根本不需要結果參數。試試這個重寫;

int find(char* a, trie_node* node) { 
    //need to make sure a is not NULL at beginning 
    int i,temp; 
    if ((a != NULL && a[0] !='\n') && node->children[a[0] - 97] == NULL) 
    { 
     return 0;//not found any children satisfied the requirement 
    } 
    else if ((a != NULL && a[0] !='\n') && 
      node->children[a[0] - 97] != NULL) 
    { 
     temp = a[0]; 
     a++; 
     return find(a, node->children[temp - 97]); 
    } 
    //a == NULL, which means end of the find procedure, just return the num_children 
    return node->num_children; //most inner one 
} 
+0

感謝您的回覆!我在哪裏添加這個 –

+0

找到函數的第10行... – cleblanc

+0

這是有效的!萬分感謝! –

1

我不明白你的問題,但我認爲這是你想要做的。當您調用該函數時,可能會忘記捕獲第二個if塊中的返回值。 (但爲什麼你將該結果參數傳遞給函數?我認爲那裏沒有用處。)

int find(char* a, trie_node* node, int result){//need to make sure a is not NULL at beginning 

    int i,temp; 
    if ((a != NULL && a[0] !='\n') && node->children[a[0] - 97] == NULL) 
    { 
     result = 0;//not found any children satisfied the requirement 
    } 
    else if ((a != NULL && a[0] !='\n') && node->children[a[0] - 97] != NULL){ 
     temp = a[0]; 
     a++; 
     result= find(a, node->children[temp - 97], result); 
    } else{//a == NULL, which means end of the find procedure, just return the num_children 
     result = node->num_children; //most inner one 
    } 
    return result; 
}