I am trying to store list of files in a char** variable.
scandir() finishes properly but I get a segmentation fault when trying to print the char**.
Here\'s the co
modify the code, it works!
#include
#include
#include
#include
#include
void makeList(char ***fileList, int* noOfFiles, char* path){
struct dirent **fileListTemp;
*noOfFiles = scandir(path, &fileListTemp, NULL, alphasort);
int i;
*fileList = (char**)malloc(*noOfFiles * sizeof(char*));
printf("total: %d files\n",*noOfFiles);
for(i = 0; i < *noOfFiles; i++){
(*fileList)[i] = (char*)malloc(strlen(fileListTemp[i] -> d_name)+1);
strcpy((*fileList)[i], fileListTemp[i] -> d_name);
printf("%s\n",(*fileList)[i]);
}
return;
}
int main()
{
char** fileList;
int noOfFiles;
char* path = ".";
makeList(&fileList, &noOfFiles, path);
return 0;
}
fileList
is type of char ***
, so *fileList
is the fileList
variable in main function.
*fileList = (char**)malloc(*noOfFiles * sizeof(char*));
with this statement, *fileList
points to allocated memory of array of pointers.
if want to allocate memory for each pointer within the array, we need use (*fileList)[i]
, other than *fileList[i]
, the precedence of []
is higher than *
.