我想要一个返回给定目录的内容的函数。为此,我从dirent.h
使用scandir
。下面的代码成功编译(gcc -Wall test.c),但最后一个printf导致分段错误。这意味着在函数后面的“eps”结构(指向指向结构的指针数组的指针)仍然是空的:我该如何解决这个问题?在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;
}
谢谢,在典型的“指向指针...”的例子中有明确的答案......我需要将它刻在我的头上! – tflutre