Add func出了点问题

时间:2019-08-23 09:25:01

标签: c

当我打印链接列表countryName时,值始终与最后一个字符串保持一致。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct usa_primaries * ptr;

typedef struct primariesDate{
    int month;
    int day;
    int hour;
}primariesDate;

 typedef struct usa_primaries{
primariesDate date;
char *countryName;
int isOpen;
ptr next;
}usa_primaries;

void add (int month, int day, int hour, char *country, int isOpen, ptr *head) {
    ptr t;
    t = (ptr) malloc(sizeof(usa_primaries));

    t->date.month = month;
    t->date.day = day;
    t->date.hour = hour;
    t->countryName = (char *)  malloc(strlen(country)+1);
    strcpy(t->countryName, country);
    t->isOpen = isOpen;

    if(!(*head)) {
        t->next = NULL;
        *head = t;
    }
    else {
        t->next = *head;
        *head = t;
    }

下面是main函数,我试图仅打印countryName详细信息,但我看到的只是插入的最后一个值。例如:scanf:test1,test2输出是:test2 test2

int main() {
    ptr head = NULL;
    int month, day, hour, isopen;
    char country[20];
    while (scanf("%d %d %d %s %d", &month, &day, &hour, country, &isopen) != EOF) {
        add(month, day, hour, country, isopen, &head);
    }
    ptr print = head;
    while (print) {
        printf("\n %s ", head->countryName);
        print = print->next;
    }

    free(head);
    return 0;
}

1 个答案:

答案 0 :(得分:2)

while (print) {
    printf("\n %s ", head->countryName);
    //               ^^^^
    print = print->next;
}

您仅打印循环中的打印头。您应该打印当前节点:

while (print) {
    printf("\n %s ", print->countryName);
    //               ^^^^^
    print = print->next;
}