[英]Nested structs and linked lists in c - Segmentation Error
I have a set of structures which I need to use to make a linked list like so:我有一组结构,我需要使用它们来制作这样的链表:
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;
This is my function that is supposed to add new nodes to the list every time it's called:这是我的 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*/
}
}
The head_node
is declared globally as event_t *head_node = NULL
. head_node
全局声明为event_t *head_node = NULL
。 However, every time I call this function in GCC I run into a segmentation error and can't resolve it.但是,每次我在 GCC 中调用此 function 时都会遇到分段错误并且无法解决。 Please help.请帮忙。
You are writing to head_node
with your scan_f
calls.您正在使用scan_f
调用写入head_node
。 Those should be writing to new_node
.那些应该写到new_node
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.