How to properly use scandir() in c?

前端 未结 4 904
独厮守ぢ
独厮守ぢ 2021-02-06 10:42

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

4条回答
  •  忘了有多久
    2021-02-06 11:12

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

提交回复
热议问题