c中的嵌套结构和链表-分段错误



我有一组结构,我需要使用它们来制作一个链表,如下所示:

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中调用此函数时,都会遇到分段错误,无法解决。请提供帮助。

您正在使用scan_f调用写入head_node。这些人应该写信给new_node

最新更新