C:从递归调用中返回一个值

时间:2017-04-03 20:33:48

标签: c recursion

generateMoveRequest

我正在尝试从此函数返回结果。由于它是一个严格的c程序,我需要在函数末尾的return语句。

在gdb中跟踪之后,最内部的函数调用返回正确的结果数。但是,在返回外部函数期间,结果的值会丢失。因此,此函数将返回0,这是错误的。我怎么能从最里面的电话回来并保持价值呢?

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分: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;
}
相关问题