【发布时间】:2015-02-22 03:16:08
【问题描述】:
我正在编写一个 c 程序来从目录中读取文件和目录,然后指向在结构的数据中找到的元素的数量,并在同一结构的数据中指向动态数组中元素的名称.我做到了,它的输出是正确的。问题是当我运行程序时出现“分段错误(核心转储)”。
代码:
#include <stdio.h>
#include <dirent.h>
#define EXIT_FAILURE 1
typedef struct FileDir
{
int *n_files;
char *file_name[];
} FileDir;
int get_files_within_dir(struct FileDir *fd)
{
DIR *dir;
int n_files;
int index;
n_files = 0;
if ((dir = opendir ("/tmp")) != NULL) {
/* counts all the files and directories within directory */
while (readdir (dir) != NULL) {
n_files++;
}
closedir (dir);
} else {
/* could not open directory */
perror ("");
return EXIT_FAILURE;
}
char *file_name[n_files];
struct dirent *ent;
if ((dir = opendir ("/tmp")) != NULL) {
/* gets all the files and directories within directory */
index = 0;
while ((ent = readdir (dir)) != NULL) {
file_name[index++] = ent->d_name;
}
closedir (dir);
} else {
/* could not open directory */
perror ("");
return EXIT_FAILURE;
}
fd->n_files = n_files;
fd->file_name[0] = file_name[0];
fd->file_name[1] = file_name[1];
fd->file_name[2] = file_name[2];
fd->file_name[3] = file_name[3];
return 0;
}
int main()
{
struct FileDir fd;
get_files_within_dir(&fd);
printf("%d\n", fd.n_files);
printf("%s\n", fd.file_name[1]);
printf("%s\n", fd.file_name[2]);
printf("%s\n", fd.file_name[3]);
return 0;
}
输出:
[freitas@localhost src]$ ./file_dir
21
..
geany_socket.fcda02b3
tmpiSdUX3
Segmentation fault (core dumped)
有趣的是,如果我只是将小于或等于 2 个值指向结构数据的动态数组,则不会显示错误消息。你有什么想法吗?
谢谢!
【问题讨论】:
-
尝试使用调试器
标签: c arrays pointers dynamic struct