[英]C: return a value from a recursive call
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语句。 您也完全不需要result参数。 试试这个重写;
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
}
我不明白您的问题,但是我想这就是您想要做的。 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.