CS将字符串转换为数组c

问题描述:

我试图读取目录中的文件并将每个文件名存储在字符串数组中。我无法让它为我的生活工作。这里的功能:CS将字符串转换为数组c

char *readFile(char *dir){ 
char *fileStringArray[1000]; 
DIR *dirPointer; 
int file_count = 0; 
struct dirent *file; 
struct stat fileType; 
int i = 0; 
if ((dirPointer = opendir(dir)) == NULL){ 
    printf("Directory not found, try again\n"); 
    return NULL; 
}else{ 
    printf("Reading files in directory\n"); 
    while((file = readdir(dirPointer)) != NULL){ //iterate through contents of directory 
    stat(dir, &fileType); 
     if(i > 1){ //ignore . and .. directories that appear first 
      file_count++; 
      printf("%s\n", file->d_name); 
      strcpy(fileStringArray[i-2], file->d_name); //crashes, replace 
      //with [i] to not crash, but i-2 makes more sense to me 
      //fileStringArray[i-2] = &file->d_name; alternate idea 
     } 
     else{ 
      i++; 
     } 
    } 
    int j; 
    for(j = 0; j < file_count; j++){ 
     printf(":::%s\n", fileStringArray[j]); //print the string array 
    } 
} 
printf("Done reading\n\n"); 
closedir(dirPointer); 
return dir; 
} 
+1

'fileStringArray'是一个* uninitialised *指针的数组。任何对这些值的访问(即'strcpy(fileStringArray [i-2],file-> d_name)')都会导致未定义的行为。为每个想要先存储的字符串分配内存。 – kaylum

+0

你正在看C书吗?从统计角度来看,我把我的赌注放在“不”,因为看起来读书的人没有这种基本问题...... – Sebivor

你的代码有两个问题。主要的一点是你试图将你的字符串存储在1000个指向字符的指针数组中。指向char的指针不足以存储字符串,它实际上需要指向一些内存。你可以用很多方法解决它,考虑将你的strcpy函数改为strdup - 它会为你分配内存。或者您需要将您的fileStringArray更改为字符数组的字符串(char fileStringArray [1000] [100])。

第二个问题是与,你应该无条件地增加它,如果你真的想在你的阵列前进。

此外,如果您可以发布完整示例,那就太好了,所以我不必猜测包含的标题。

+0

对不起,我不想发布我的项目的其余部分,heres头文件:#include 的#include 的#include 的#include 的#include 的#include 的#include cowchin12