【问题标题】:Char ** keeps getting overwritten when recursivley adding to itChar ** 在递归添加时不断被覆盖
【发布时间】:2020-07-07 08:20:52
【问题描述】:

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

Main.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;
}

Headers.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

【问题讨论】:

    标签: c arrays pointers heap-memory dynamic-memory-allocation


    【解决方案1】:

    来自this readdir reference

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

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

    所以当你这样做时

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

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

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

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

    当然,完成后,您需要free 数组中的每个字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-13
      • 2014-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多