#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
哪裏是錯誤和如何解決它?
我不相信該程序編譯。另外,不要施加'malloc'的結果。 –
@KerrekSB,猜測一個C++編譯器正被用來解決'malloc()'中缺少'struct'關鍵字和從'malloc()'中返回值的轉換。 – hmjd
@hmjd:在這種情況下,我應該推薦使用'std :: list':-) –