我编写了这些结构和函数来添加链接列表的链接,但是我得到了分段错误。为什么会这样?
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;
}
我认为问题在于日期结构的内存分配,但不确定。
答案 0 :(得分:2)
您正在temp
上进行迭代,直到它等于NULL
,然后您将其取消引用它。你的while循环的条件应该是temp->next != NULL
。