今天,我非常有信心在考试中取得 100% 的成绩,但我浪费了所有时间来尝试修复此错误,不用说我从未完成,而且我对此感到非常厌倦。想法是:
typedef struct Poly{
int x;
int y
struct Poly *next;
}Poly;
Poly *add_poly();
int main(){
Poly *a = (Poly*)malloc(sizeof(Poly));
a = add_poly(); //so this should be ret, the first 2 ints i typed should be here
printf("%dx^%d",a->x,a->y); //this works
a=a->next;
printf("%dx^%d",a->x,a->y); //this crashes.
}
Poly *add_poly(){
Poly *temp = (Poly*)malloc(sizeof(Poly));
Poly *ret = (Poly*)malloc(sizeof(Poly));
temp = ret; //make sure i get to keep the header of the list?
while(1){
scanf("%d %d",&x,&y);
temp->x=x;
temp->y=y
printf("%dx^%d",temp->x,temp->y);//authentication
temp=temp->next;
temp=(Poly*)malloc(sizeof(Poly));
if(y==0){
temp->x=0;
temp->y=0;
break;
}
}
return ret;
}
我不明白!我以前曾在更复杂的编码中使用过链表,但我从未遇到过这个问题,我一定是漏掉了一些东西,但我浪费了 1 分 30 小时试图找出考试中的错误,回家后又浪费了 2 个小时,同样的错误,即使我实际上删除并从头开始重新输入每个命令......
最佳答案
仅在需要时分配一个节点。在向前迈出一步之前,分配 next
指向的节点。
Poly *add_poly(){
Poly *ret = (Poly*)malloc(sizeof(Poly)); // allocate first node
ret->next = NULL; // successor of first node is NULL
Poly *temp = ret;
while(1)
{
scanf("%d %d", &temp->x, &temp->y); // read data
printf("%dx^%d", temp->x, temp->y); // print data
if ( temp->y==0 ) // terminate if y == 0
break;
temp->next = (Poly*)malloc(sizeof(Poly)); // allocate next node right to target
temp = temp->next; // step one forward
temp->next = NULL; // successor of last node is NULL
}
return ret;
}
如果不需要,就不要分配内存。 a
由函数add_poly
的返回值设置。如果您将内存分配给 main
中的 a
,则会发生内存泄漏。除此之外,不要忘记在程序结束时释放
你的内存。
int testmain(){
Poly *a = add_poly(); // read data and create list
Poly *temp = a
while ( temp != NULL ) // print data from list
{
printf("%dx^%d",temp->x,temp->y);
temp = temp->next;
}
while ( a != NULL ) // free list
{
temp = a->next;
free( a );
a = temp;
}
return 0;
}
关于C - 为什么我不能读取模块中的链接列表并返回 main 中的 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35224111/