在下面的代码中,您可以看到用 C 语言实现的基本整数链表。 我编写了两个不同的函数来在列表前面插入一个新的 int-val 。 我认为这两个函数是等价的,但输出显示它们不是等价的。
#include <stdio.h>
#include <stdlib.h>
typedef struct _IntlistElem* Intlist;
typedef struct _IntlistElem {int val; Intlist next;} IntlistElem;
Intlist insertfirst(int val, Intlist list) {
Intlist new = malloc(sizeof(IntlistElem));
new->val = val;
new->next = list;
return new;
}
Intlist insertfirstAlternative(int val, Intlist list) {
IntlistElem new = {val, list};
Intlist head = &new;
return head;
}
void print(Intlist l){
while (l!=NULL){
printf("%d\n", l->val);
l = l->next;
}
printf("_____\n");
}
int main(){
Intlist ls = NULL;
ls = insertfirst(2, ls);
ls = insertfirst(1, ls);
print(ls);
Intlist lsAlt = NULL;
lsAlt = insertfirstAlternative(2, lsAlt);
lsAlt = insertfirstAlternative(1, lsAlt);
print(lsAlt);
return 0;
}
输出:
1
2
_____
1
1
...
我的问题是:
1.
为什么打印功能没有终止? (调用替代函数后)
2.
为什么这两个“insertfirst”函数与我预期的不同?
这些功能有什么区别?
我期待着您的答复。 :)
最佳答案
您的函数insertfirstAlternative
返回一个指向head
的指针。该变量的生命周期在函数返回时结束。因此,它返回一个无效的指针值。
The value of a pointer becomes indeterminate when the object it points to reaches the end of its lifetime.
任何事情都可能发生。
在您的情况下,第二次调用该函数时,第二个 head
是在与第一个相同的地址创建的,因此 next
指针指向相同的目的。因此,无限循环。
关于C:链接列表 - 函数 "insert first"未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38192618/