gpt4 book ai didi

c - 如何为C中链表内的结构分配内存?

转载 作者:行者123 更新时间:2023-11-30 18:49:34 25 4
gpt4 key购买 nike

我编写了这些结构和函数来添加链接到链表,但出现段错误。为什么会发生这种情况?

typedef struct primaries_date{
int day;
int month;
int time;
} primaries_date;

typedef struct usa_primaries {
primaries_date *date;
char *state;
int open;
struct usa_primaries *next;
} usa_primaries;

usa_primaries *head = NULL;

void insert(int day, int month, int time, char *state, int open){
usa_primaries *temp, *entry = (usa_primaries *)malloc(sizeof(usa_primaries));
entry->date = (primaries_date *)malloc(sizeof(primaries_date));
if(entry == NULL || entry->date==NULL){
printf("error couldnt allocate memory");
return;
}
entry->date->day = day;
entry->date->month = month;
entry->date->time = time;
entry->state = state;
entry->open = open;

if(head ==NULL){
head = entry;
} else {
temp = head;
while(temp!=NULL)
temp = temp->next;
temp->next = entry;
}
entry->next = NULL;
}

我认为问题出在日期结构的内存分配上,但不确定。

最佳答案

您正在迭代 temp 直到它等于 NULL,然后您将取消引用它。 while 循环的条件应该是 temp->next != NULL

关于c - 如何为C中链表内的结构分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42457649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com