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

C:从递归调用返回一个值,c,recursion,C,Recursion,我试图从这个函数返回结果。因为它是一个严格的c程序,所以我需要在函数末尾使用一个return语句 在gdb中跟踪它之后,最内部的函数调用将返回正确的结果编号。但是,返回到外部功能时,结果值丢失。因此,此函数将返回错误的0。如何从最里面的调用返回并保留值?您只需要添加return语句。您也根本不需要result参数。尝试重新编写 int find(char* a, trie_node* node, int result){//need to make sure a is not NULL at b

我试图从这个函数返回结果。因为它是一个严格的c程序,所以我需要在函数末尾使用一个return语句


在gdb中跟踪它之后,最内部的函数调用将返回正确的结果编号。但是,返回到外部功能时,结果值丢失。因此,此函数将返回错误的0。如何从最里面的调用返回并保留值?

您只需要添加return语句。您也根本不需要result参数。尝试重新编写

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;
}

我不明白你的问题,但我认为这就是你想要做的。调用函数时,可能忘记了在秒if块中捕捉返回值。但是为什么要将结果参数传递给函数呢?我认为那没有用

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
}

谢谢回复!我在哪里添加这个虽然正确,但我投了反对票,因为这损害了函数的风格。请看另一个答案。最好将递归值赋给result=…@WeatherVane实际上最好不要使用未使用的result参数…@WeatherVane好的,我接受了你的建议。为什么你的函数有result参数?它的值从未被使用过。@melpomene最初,我在add函数中没有这个值。然而,由于我需要在函数末尾返回结果,所以我认为最好使用一个参数作为全局变量,它可以存储来自内部函数的值。这就是我添加结果的原因。参数是局部变量。作为全局变量的参数是没有意义的。是的,我在gdb中跟踪了这段代码,发现它不是作为全局变量的。谢谢你指出这一点!97这个神奇的数字是干什么用的?那是‘a’吗?
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;
}