簡體   English   中英

c 中的嵌套結構和鏈表 - 分段錯誤

[英]Nested structs and linked lists in c - Segmentation Error

我有一組結構,我需要使用它們來制作這樣的鏈表:

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;

這是我的 function 應該在每次調用時將新節點添加到列表中:

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 中調用此 function 時都會遇到分段錯誤並且無法解決。 請幫忙。

您正在使用scan_f調用寫入head_node 那些應該寫到new_node

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM