c - 我的 malloc 结构出现段错误 11

标签 c pointers struct file-io malloc

我正在尝试从一个文本文件中读取,该文件的第一个值是文本中的条目数量。使用此值,我将创建一个 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/

相关文章:

c - 如何动态分配包含多个数组的结构体?

c - redisAsyncConnect() 与 redisConnect() 有何不同?

c++ - 是否可以在 C++ 中动态分配临时变量?

c - 数组指针 while 循环输入

c - 使用 Malloc() 使用指针创建整数数组

c - 8 位输入给出奇怪的行为,因为 16/32 位给出小端/大端

C函数原型(prototype)

c - 有效地对结构数组进行排序

c - Malloc Typedef 结构问题

c - C程序中变量的值不变