gpt4 book ai didi

C:递归调用返回一个值

转载 作者:行者123 更新时间:2023-11-30 18:36:03 24 4
gpt4 key购买 nike

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 程序,因此我需要在函数末尾添加一个 return 语句。

在 gdb 中跟踪它后,最内部的函数调用返回正确的数字结果。然而,在返回到外部函数的过程中,结果的值会丢失。因此,该函数将返回 0,这是错误的。我如何返回并保留最内层调用的值?

最佳答案

您只需要添加 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
}

关于C:递归调用返回一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43193752/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com