gpt4 book ai didi

C - 指向结构体 "Segmentation fault (core dumped)"中的动态数组的指针

转载 作者:行者123 更新时间:2023-11-30 17:20:14 24 4
gpt4 key购买 nike

我正在编写一个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 个值指向结构体数据的动态数组,则错误消息不会显示。你有什么想法吗?

谢谢!

最佳答案

您有 2 个问题可能导致段错误

  1. n_files 字段是一个指针,并且您为其分配了一个整数,它应该声明为

    int n_files;
  2. 您不必为 file_name 字段分配空间,您至少应该提供一个固定大小,如下所示

    char *file_name[1000];

    您可以使用malloc()动态分配内存,但这是另一回事,需要解释。

注意:启用编译器警告将帮助您防止愚蠢的错误,例如 int *n_files 然后执行 fd->n_files = n_files;

关于C - 指向结构体 "Segmentation fault (core dumped)"中的动态数组的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28654096/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com