C - 从递归返回后指针值发生变化

标签 c recursion

递归调用后fileB和entry->d_name的值发生变化(backup(fileB,entry->d_name, archive_file)),为什么?我该如何解决这个问题?提前致谢!

else if(S_ISDIR(h.kind))
{
    printf("\nits a directory #######\n");
    struct dirent* entry = NULL;
    DIR* dir = opendir(h.name);
    if (dir == NULL) {
        printf("Directory couldn't be opened\n");
        exit(1);
    }

    while ((entry = readdir(dir))) {
        printf("\n %s ********** \n %s ******* \n\n" , entry->d_name,fileB );
        if (strcmp(".", entry->d_name) != 0 && strcmp("..", entry->d_name) != 0) {
            printf("before recursion    entry= %s   ,  fileB= %s \n",entry->d_name,fileB);
            backup(fileB,entry->d_name, archive_file);
            printf("after recursion     entry= %s   ,  fileB= %s \n",entry->d_name,fileB);
        }
    }

    if (closedir(dir)) {
        printf("close dir error");
        exit(1);
    }
}

enter image description here

最佳答案

首先在备份函数中,您应该更改 const char* xxx 的参数。因为您不打算修改这些。因此,您将在函数中创建一个新的 char[] 或 char* :

char tmp[]; //you might have to give tmp specific size, use strlen()
strcpy(tmp, path);
strcat(tmp, "/");
strcat(tmp, fileB);

不确定它是否能解决您的问题,但有可能。

关于C - 从递归返回后指针值发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41692690/

相关文章:

java - 递归方法上的 StackOverflowError

c - Windows 上混合 Julia 和 C 项目的最小工作示例

c - 在 C 中打印字符串时出现无法解释的行为

python - 尝试模块化 python 代码但出现递归错误 : maximum recursion depth

java - 使用各种字段递归解析字符串的最佳方法

Java - 接受用户的不同按键来执行不同的任务,当用户单击时终止 "X"

windows - 从 Windows 文件系统中递归删除 .listing 文件

c - 为什么我在 Windows 机器上用 C 开发时会出现 include <windows.h> 错误?

从 token 和宏的串联创建类似对象的宏

c - 为什么我在这里得到错误的答案?