奇怪的值添加到列表中

时间:2013-01-08 12:05:42

标签: c list

#include <stdlib.h>
#include <stdio.h>


struct a
{
    a * next;
    double v;
};


void add(struct a* list,double d)
{
    if(!list->next) goto exception; //I know that a lot of programmers have a low opinion about "goto"

    list=list->next;

    list->v=d;

    return;

exception:
    printf("Cannot add a new element to the list\n");
}

int main()
{
    struct a l;
    double j;
    int i;

    for(j=1.0; j<10.0; j+=1.0)
    {   
        l.next= (a*)malloc(sizeof(a));
        add(&l,j);
        printf("%lf ",l.v);
    }
    return 0;
}

这个程序编译,但输出中有一个混乱:

  

-9255963134931783100000000000000000000000000000000000000000000000000.000000 -92559631   349317831000000000000000000000000000000000000000000000.000000 -92559631349317831   000000000000000000000000000000000000000000000.000000 -92559631349317831000000000   000000000000000000000000000000000000.000000 -92559631349317831000000000000000000   000000000000000000000000000.000000 -92559631349317831000000000000000000000000000   000000000000000000.000000 -925596313493178310000000000000000000000000000000000000000   000000000.000000 -92559631349317831000000000000000000000000000000000000000000000   .000000 -92559631349317831000000000000000000000000000000000000000000000.000000

期望的是:

1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0

错误在哪里以及如何解决?

1 个答案:

答案 0 :(得分:7)

问题是l.v中的main() 从未分配了值add()将值分配给l.next。调用者无法看到listlist->next的分配,因此l中的main()始终是struct a的同一个实例。这意味着prinf()正在打印相同的联合double

其他要点:

  • 正确初始化l

    struct a l = { NULL, 0 };
    
  • malloc()内存next struct a add() next内的所有成员。
  • 访问main()中的最新struct a,例如,从add()返回最新{{1}}的地址。
  • Don't cast the return value of malloc()(并使用C编译器)。