C:链接列表 - 函数 "insert first"未按预期工作

标签 c pointers linked-list malloc

在下面的代码中,您可以看到用 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/

相关文章:

c++ - C++ 反转链表

c - 使用递归算法反转链表

objective-c - 如何使用 Objective-C 测试数字是否在范围内?

c - 字符串突然变空,即使它在片刻之前是完整的

c - C 中的 Boss Worker Pthreads Web 服务器 - 如果发送的请求多于线程数,服务器会崩溃

c++ - 指针在赋值前会占用内存吗?

c++ - 返回指向常量 getter 的指针时,返回值类型与函数类型不匹配

java - 如何将 Java 函数转换为 C 函数?

c++ - 我可以在指针类型的声明中省略 const 限定符吗?

java - 哈希表中的链表