如何在c中的链接列表中为结构分配内存



我编写了这些结构和功能,以将链接添加到链接列表中,但我会得到分割故障。为什么会发生?

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,然后您将其提出。您的W循环的状况应为temp->next != NULL

相关内容

  • 没有找到相关文章

最新更新