【问题标题】:Nested structs and linked lists in c - Segmentation Errorc中的嵌套结构和链表 - 分段错误
【发布时间】:2023-03-21 02:35:01
【问题描述】:

我有一组结构,我需要使用它们来制作这样的链表:

typedef struct {         
 int tm_min;
 int tm_hour;
} event_time_t;

typedef struct {          
 int tm_mday;
 int tm_mon;
 int tm_year;
} event_date_t;

typedef struct event_t {          
 char title[20];         
 event_time_t *time;
 event_date_t *date;
 struct event_t *next;
} event_t;

这是我的函数,应该在每次调用时向列表中添加新节点:

void add_events(void) {
  event_t *new_node = NULL;
  event_t *temp_node = NULL;

  new_node = (event_t*) malloc(sizeof(event_t)); /*allocate memory to the node*/
  new_node->time = (event_time_t*) malloc(sizeof(event_time_t));
  new_node->date = (event_date_t*) malloc(sizeof(event_date_t));
  new_node->next = NULL;

  scanf("%s", &head_node->title); /*assign values to the node from the user*/
  scanf("%d", &head_node->time->tm_hour);
  scanf("%d", &head_node->time->tm_min);
  scanf("%d", &head_node->date->tm_mon);
  scanf("%d", &head_node->date->tm_mday);
  scanf("%d", &head_node->date->tm_year);

  if (head_node == NULL) { /*if there is only a head node, set it equal to new_node*/
    head_node = new_node;
  }
  else {
    temp_node = head_node;
    while (temp_node->next != NULL) { /*find the latest linked node*/
      temp_node = temp_node->next;
    }
    temp_node->next = new_node; /*link the new node to the latest node*/
  }


}

head_node 被全局声明为event_t *head_node = NULL。但是,每次我在 GCC 中调用此函数时都会遇到分段错误并且无法解决它。请帮忙。

【问题讨论】:

  • 哪行代码导致错误?你的意见是什么?
  • @RobertHarvey 输入应该来自一个重定向的文本文件,该文件包含如下事件列表:生日 12 30 10 01 2018 婚礼 06 30 06 15 2018
  • @RoberHarvey 我不知道是哪条线路导致了问题,我已经坚持了好几个小时......
  • 分段错误很可能是由于 scanf() 行上可能取消引用 NULL 指针,因为那时 head_node 可能尚未初始化。
  • @AntoninGAVREL 感谢您的输入,但如果我理解正确的话,我相信我在 while 循环中有这种情况。

标签: c data-structures struct linked-list


【解决方案1】:

您正在使用您的scan_f 电话写信给head_node。那些应该写信给new_node

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    • 2016-09-17
    • 2021-02-13
    • 1970-01-01
    • 2012-11-24
    • 2011-08-24
    相关资源
    最近更新 更多