我正在尝试从一个文本文件中读取,该文件的第一个值是文本中的条目数量。使用此值,我将创建一个 for 循环,将日期和文本分配到特定的结构中,直到所有条目都已放入结构中。它还将通过每个 for 循环打印值。然而,在编译时,它给出了段错误:11。你能解释一下吗,我不太擅长结构和malloc。 预先感谢您。
(请注意,打印的文本日期故意与我的作业文本文件中的日期不同)。
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include"journal.h"
int main(int argc, char* argv[])
{
FILE* journal;
int i, numentries;
Entry* entries;
Entry* temp;
if (argc != 2)
{
printf("Index required");
}
fscanf(journal, "%d", &numentries);
entries = (Entry*)malloc((numentries)*sizeof(Entry));
for(i=0; i<numentries; i++)
{
fscanf(journal,"%2d/%2d/%4d", &entries[i].day, &entries[i].month, &entries[i].year);
fgets(entries[i].text, 101, journal);
printf("%4d-%2d-%2d: %s", entries[i].year, entries[i].month, entries[i].day, entries[i].text);
}
fclose(journal);
return 0;
}
我的头文件(日志)是 ->
typedef struct {
int day;
int month;
int year;
char text[101];
}Entry;
Entry entries;
文本文件的示例如下:
2
12/04/2010
Interview went well i think, though was told to wear shoes.
18/04/2010
Doc advised me to concentrate on something... I forgot.
最佳答案
这是一个有效的最小示例:
修改:
- 正在打开文件并检查文件是否无法打开
- 更正了输入格式字符串(在
fscanf
中添加了\n
)
可选修改(程序在没有它们的情况下也可以工作):
- 从
malloc
中删除了强制转换 - 在使用变量时声明变量
- 删除了无用的变量
- 在
malloc
中使用sizeof(*entries)
代替sizeof(Entry)
- 使用
sizeof(entries->text)
代替硬编码值101
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct {
int day;
int month;
int year;
char text[101];
}Entry;
Entry entries;
int main(int argc, char* argv[])
{
FILE* journal = fopen("yourfile", "r");
if (journal == NULL)
{
printf("Cannot not open file\n");
return 1;
}
int numentries;
fscanf(journal, "%d", &numentries);
Entry* entries = malloc(numentries * sizeof(*entries));
for (int i = 0; i<numentries; i++)
{
fscanf(journal, "%2d/%2d/%4d\n", &entries[i].day, &entries[i].month, &entries[i].year);
fgets(entries[i].text, sizeof(entries->text), journal);
printf("%4d-%2d-%2d: %s", entries[i].year, entries[i].month, entries[i].day, entries[i].text);
}
fclose(journal);
return 0;
}
除了无法打开文件的情况外,仍然不执行任何错误检查。这留给读者作为练习。
关于c - 我的 malloc 结构出现段错误 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46581059/