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

该程序可以编译,但输出中出现一团糟:

-92559631349317831000000000000000000000000000000000000000000000.000000 -92559631 349317831000000000000000000000000000000000000000000000.000000 -92559631349317831 000000000000000000000000000000000000000000000.000000 -92559631349317831000000000 000000000000000000000000000000000000.000000 -92559631349317831000000000000000000 000000000000000000000000000.000000 -92559631349317831000000000000000000000000000 000000000000000000.000000 -92559631349317831000000000000000000000000000000000000 000000000.000000 -92559631349317831000000000000000000000000000000000000000000000 0.000000 -92559631349317831000000000000000000000000000000000000000000000.000000

而想要的是:

1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0

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

4

1 回答 1

7

问题是l.vin从来没有main()被赋值为赋值给. to的分配对调用者不可见,因此in始终是 的相同实例。这意味着正在打印相同的 unialized 。add()l.nextlistlist->nextlmain()struct aprinf()double

其他要点:

  • 正确初始化l

    struct a l = { NULL, 0 };
    
  • malloc()内部next实例的内存并初始化所有成员。struct aadd()
  • 访问最新next的,例如main()通过返回最新的struct a地址add()
  • 不要强制转换malloc()(并使用 C 编译器)的返回值。
于 2013-01-08T12:10:53.687 回答