【问题标题】:Failed implementation of a Linked List in CC 中的链表实现失败
【发布时间】:2020-04-29 17:35:29
【问题描述】:

我不明白为什么这个程序不工作并且元素没有按预期插入到列表中。

每次在调试的时候,看到在'insert'方法之后去main方法时,Linked List还是空的,我不明白为什么,因为我认为应该没问题,因为我正在使用指针(这似乎是一个“悬空指针”案例,但如果是,我不明白为什么)。

也许我应该使用双星 (**)? 如果是,为什么在数组中没关系?

这里是源代码:

#include <stdio.h>
#include <stdlib.h>

struct A{
    int val;
    struct A* next;
} A;

void insert(struct A* L, int newVal) {

    if (L == NULL) {

        L = (struct A*) malloc(sizeof(struct A));
        L->val = newVal;
        L->next = NULL;
    }

    else {

        struct A* p = L;

        while (p->next != NULL) {

            p = p->next;
        }

        p->next = (struct A*) malloc(sizeof(struct A));
        p->next->val = newVal;
        p->next->next = NULL;
    }
}


void printA(struct A* printed) {

    struct A* p = printed;

    while (p != NULL) {
        printf("%d\n", p->val);
        p = p->next;
    }
}


int main() {

    struct A* L = NULL;

    insert(L, 1);
    printf("1 success\n");

    insert(L, 2);
    printf("2 success\n");

    insert(L, 3);
    printf("3 success\n");

    insert(L, 4);
    printf("4 success\n");

    insert(L, 5);
    printf("5 success\n");

    printf("\n\n\n");

    printA(L);

    return 0;
}

谢谢。

【问题讨论】:

  • 您总是将NULL 传递给insert()
  • 传递指针的时候,如果你想在子函数中修改那些内容,那么你必须传递指针的地址,而不是指针的内容,就像你必须传递的地址一样您希望子函数修改的任何其他变量

标签: c linked-list dangling-pointer


【解决方案1】:

insert函数的第一个参数是一个指向结构的指针。当你传递你的结构时,insert 接收地址,并创建一个指向同一个地方的本地指针。为了改变实际结构(来自 main)指向的内容,你必须传递一个双指针。

下面写的是需要改动的部分:

void insert(struct A** L, int newVal) {

    if (*L == NULL) {

        *L = (struct A*) malloc(sizeof(struct A));
        (*L)->val = newVal;
        (*L)->next = NULL;
    }

    else {

        struct A* p = *L;

        ...
        ...
        ...
    }
}    

int main() {

    struct A* L = NULL;

    insert(&L, 1);
    printf("1 success\n");

    ...
    ...
    ...

    printA(L);

    return 0;
}

另一种方法是保留单个指针,但将insert 的返回值更改为struct A*。您只需将返回值分配给您的 main 结构,如下所示:

struct A *insert(struct A* L, int newVal) {

    if (L == NULL) {

        L = (struct A*) malloc(sizeof(struct A));
        L->val = newVal;
        L->next = NULL;

        return L;
    }

    else {
        ...
    }

    return L;
}

int main() {

    struct A* L = NULL;

    L = insert(L, 1);
    ...
    return 0;
}

此外,您的打印功能不会移动到任何地方。添加行p = p-&gt;next;

void printA(struct A* printed) {

    struct A* p = printed;

    while (p != NULL) {
        printf("%d\n", p->val);
        p = p->next;
    }
}

【讨论】:

  • 非常感谢!
猜你喜欢
  • 2017-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-13
  • 2015-06-03
  • 1970-01-01
相关资源
最近更新 更多