簡體   English   中英

Add func出了點問題

[英]Something wrong with add func

當我打印鏈接列表的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;
}
while (print) {
    printf("\n %s ", head->countryName);
    //               ^^^^
    print = print->next;
}

您僅打印循環中的打印頭。 您應該打印當前節點:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM