c - 我无法从递归函数中正确返回

标签 c recursion

我有这个代码:

char* findFile(char* path, char* fileName)
{
DIR *thisDir;
struct dirent *dirEntry;

int notFound=1;

while (NULL != (dirEntry = readdir(thisDir)) && notFound)
{
    if (dirEntry->d_type == DT_DIR)
    {
        if (dirEntry->d_name[0] != '.')
        {
            char *nextPath = malloc(512);
            strcpy(nextPath, path);
            strcat(nextPath, dirEntry->d_name);
            nextPath[nextPathLen] = '/';
            findFile(nextPath, fileName);

        }
    }
    else if (dirEntry->d_type == DT_REG)
    {
        if (strcmp(fileName, dirEntry->d_name) == 0 )
        {
            char* foundPath = malloc (512);
            strcpy(foundPath,path);
            strcat(foundPath,fileName);
            notFound=0;
            return foundPath;
        }
    }
  }
}

函数有一次返回 foundPath 但我不知道如何从第一个函数调用中获取并返回它。我可以打印它来验证该函数是否有效,但是我该怎么做才能从 foundPath 获取该值以在另一个函数中使用它?

最佳答案

替换行

findFile(nextPath, fileName);

char * f = findFile(nextPath, fileName);
if (f != NULL)
    return f;

您需要检查返回值是否为 NULL - 如果为 NULL,您需要继续查找。

您还必须在函数末尾返回 NULL 以指示在该迭代中未找到任何内容。并非所有代码路径都返回一个值是“未定义的行为”——这意味着任何事情都可能发生。例如,如果您没有找到任何东西(即返回 NULL),您可能会返回虚假地址而不是您想要的地址。

还有一些其他问题 - 所有这些 malloc 都会导致内存泄漏并且没有释放,但是先让它工作然后再解决它。

关于c - 我无法从递归函数中正确返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40367419/

相关文章:

java - 通过递归调用继续存储变量值

c - While 循环在条件出现之前停止

C程序收银系统

c# - 为什么我在控制台中得到问号而不是 double 值/NaN,这是什么意思?

c++ - 无法让基数排序算法在 C++ 中工作

recursion - 不确定为什么 let 函数没有正确返回 sbcl lisp 中的值

C程序从字符串数组中提取不同的子字符串

c - 客户端中的 OpenSSL Bio_gets

c - 是否可以打印 free() 想要释放内存的值?

javascript - EXT JS6 递归调用 Store