0

我有一个链表,它从文件中读取一些信息并将其显示到屏幕上。一切都正确读取,但是当我去显示“秒”时,显示的数字类似于-431602080.000000而不是,例如,27.123000。我不知道为什么。

 //GLOBAL VARIABLES
    struct PlayerTime* list_head = NULL;

    void besttimes_view()
    {   
        struct PlayerTime *p;
        p = list_head;

        while(p!=NULL){
            printf("%f : %s\n", p->seconds, p->name); //This prints the name correctly, but the number is wrong. Something like -431602080.000000 : Calvin
            p = p->next;
        }
    }

有人知道发生了什么吗?

4

2 回答 2

2
while((fgets(input,MAX_STR_LEN,fileName)!=NULL)){
    p=(struct PlayerTime*)malloc(sizeof(struct PlayerTime));

您使用每个 fgets() malloc 一个新的播放时间,但每隔一个 fgets() 将其添加到列表中。您添加到列表中的那个没有设置秒数,只有名称。

换句话说,您设置的播放时间秒数永远不会被添加到列表中。只有您设置了名称的人才会添加到列表中。

    if(counter==1){
        p->seconds=atof(input); // this p is never added to the list
        printf("%f\n",p->seconds); //This prints the number as it should be (e.g. 27.123000)
    }
    if(counter==2){
        strcpy(p->name,input); // this p is added to the list
        counter=0;
        p->next=list_head;
        list_head = p;
    }
于 2013-10-01T03:53:53.537 回答
1

我将从您在分支p外部分配的事实开始。counter==1换句话说,你:

  1. allocate a new p,
  2. counter==1, so you put time in it,
  3. increase counter,
  4. allocate a new p (and discard previous one),
  5. counter==2, so you put name in it and store it,
  6. ...

I guess you want the malloc() to happen inside if (counter==1).

Then, you don't reset the counter, so every next player doesn't get anything since counter==3 and so on.

于 2013-10-01T03:54:49.837 回答