주어진 디렉터리의 내용을 반환하는 함수가 필요합니다. 이를 위해 dirent.h
에서 scandir
을 사용하고 있습니다. 아래의 코드는 성공적으로 컴파일되고 (gcc -Wall test.c), 마지막 printf는 분할 오류로 연결됩니다. 이것은 "eps"구조 (dirent 구조체에 대한 포인터 배열에 대한 포인터)가 함수 뒤에 여전히 비어 있음을 의미합니다. 어떻게 해결할 수 있습니까?C에서 함수의 인수로 전달할 때 포인터 배열에 대한 포인터의 대상을 수정하십시오.
#include <stdlib.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
static int myselector(const struct dirent * dir_entry)
{
char * pch = strstr(dir_entry->d_name, ".");
return pch == NULL ? 1 : 0;
}
int list_dir(char * dirname, struct dirent ** eps)
{
int nbfiles = scandir(dirname, &eps, myselector, alphasort);
if(nbfiles > 0)
{
printf("inside function: %s\n", eps[0]->d_name);
return 1;
}
else
return 0;
}
int main(int argc, char *argv[])
{
int status = 0;
struct dirent ** eps = NULL;
status = list_dir("/home", eps);
if (status)
{
puts("ok");
printf("outside function: %s\n", eps[0]->d_name);
}
return EXIT_SUCCESS;
}
전형적인 "pointer-to-pointer-to ..."예제에서 명확한 답변 ... 내 머리에 새겨 넣어야합니다! – tflutre