首页 > 解决方案 > Char ** 在递归添加时不断被覆盖

问题描述

我的代码应该将文件放在目录中,将它们放入字符串数组中,然后打印内容。目前在我的 Functions.c 文件中,它成功写入了正确的数组索引,但是当我写入下一个数组索引时被覆盖。任何帮助表示赞赏。

主程序

#include "Headers.h"


    void main(){
        listFiles("C:/Users/me/Documents/testDoc");
        //printf("%s",fileArray[0]);
        printf("End");
        return;
    }

函数.c

#include "Headers.h"


void listFiles(const char *foldername){
    struct dirent *dp; //creates object of struct dirent
    DIR *dir=opendir(foldername); //creates object of directory
    char **fileArray=(char **)calloc(1,sizeof(char *));
    if (!dir) //checks to see if directory exsists
        return;
    int numloops=1;
    while ((dp = readdir(dir)) != NULL)//recursivley goes through list
    {
        printf("%d\n",numloops);
        if(numloops==1){
            fileArray[0]=dp->d_name; //maps first file to position zero
            printf("%s test\n",fileArray[0]);
        }
        else{
            fileArray=realloc(fileArray,numloops*sizeof(char *));
            fileArray[numloops-1]=dp->d_name; //maps next file in order to position -1 to make enough memory since array starts at 0
            printf("%s test\n",fileArray[numloops-1]);
        }

        numloops++;
        printf("%s original\n", dp->d_name);//maps d_name recursivley
    }
    // Close directory stream
    printf("Value at index 2 %s\n",fileArray[2]);
    printf("Value at index 3 %s\n",fileArray[3]);
    closedir(dir);
    return;
}

头文件.h

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
void listFiles(const char *foldername);

输出

1
. test
. original
2
.. test
.. original
3
Doc 1.txt test
Doc 1.txt original
4
Doc 2.txt test
Doc 2.txt original
5
Doc 3.txt test
Doc 3.txt original
Value at index 2 Doc 3.txt
Value at index 3 Doc 3.txt
End

预期产出

1
. test
. original
2
.. test
.. original
3
Doc 1.txt test
Doc 1.txt original
4
Doc 2.txt test
Doc 2.txt original
5
Doc 3.txt test
Doc 3.txt original
Value at index 2 Doc 1.txt
Value at index 3 Doc 2.txt
End

标签: carrayspointersheap-memorydynamic-memory-allocation

解决方案


这个readdir参考

返回的指针和结构中的指针可能会失效,或者结构或存储区域可能会被readdir()对同一目录流的后续调用覆盖。

那句话的意思是readdir可以一遍又一遍地返回指向同一结构的指针,这意味着d_name成员每次都是相同的。

所以当你这样做时

fileArray[numloops-1]=dp->d_name;

您使数组中的所有元素都指向完全相同的内存。

解决方案是复制字符串d_name,例如

fileArray[numloops-1]=strdup(dp->d_name);

当然,一旦你完成了,你需要free数组中的每一个字符串。


推荐阅读