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

时间:2017-02-25 15:02:04

标签: c segmentation-fault

我编写了这些结构和函数来添加链接列表的链接,但是我得到了分段错误。为什么会这样?

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;
}

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

1 个答案:

答案 0 :(得分:2)

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