【问题标题】:Pointers issue in linked list function's return I cannot figure链表函数返回中的指针问题我不知道
【发布时间】:2016-12-10 13:05:58
【问题描述】:

调试时,它告诉我 L 是 nullptr。我不知道为什么它不能正确返回列表。

这些是结构体(我必须使用列表和节点):

typedef struct node node;
typedef struct List list;
struct node {
    int data;
    node *next;          
};

struct List {
    node *head;
};

创建列表的函数:

void BuildList(list *L) {
    node *head = NULL, *temp = head;
    int num;
    printf("Input list's elements: \n");
    do {
        scanf("%d", &num);
        if (num != -1) {
            if (head == NULL) {
                head = BuildNode(num);
                temp = head;
            }
            else {
                temp->next = BuildNode(num);
                temp = temp->next;
            }
        }

    } while (num != -1);

    L = (list *) malloc(sizeof(list));
    L->head = head;
}

BuildList 的辅助功能:

node* BuildNode(int num1) {
    node *node1 = (node *)malloc(sizeof(node));

    node1->data = num1;
    node1->next = NULL;

    return node1;
}

打印功能:

void PrintList(list *L) {
    node *head;
    head = L->head;
    printf("The list's elements are: ");

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

程序在“head = L->head;”上失败在 PrintList,声称它是一个 nullptr。它的起源可以证明是最后在BuildList中的动态分配。来自 main 的调用是:

list *head = NULL;
BuildList(&head);
PrintList(head);

当替换 PrintList(head);与打印列表(&头);它打印一个空列表,不会失败。

【问题讨论】:

  • 你在哪里分配了头?
  • 哪个头?在 BuildList 或 main 中?在 BuildList 中,head 被称为 L.

标签: c debugging pointers singly-linked-list


【解决方案1】:

你正在传递一个指向函数的指针:

构建列表(列表 *L)

这意味着当你在函数内部分配它时,你不会在这个函数之外有这个指针,因为它在堆栈上。您可以做的是,在此函数之外分配 List ,例如:

list *head = malloc(sizeof(list)); /* It's a good habit to not cast malloc function */ 
BuildList(head); /* Remember to remove malloc from inside of build list */
PrintList(head);

或者将双指针传递给函数:

void BuildList(list **L) {
    node *head = NULL, *temp = head;
    .....
    *L = malloc(sizeof(list));
    (*L)->head = head;
}

list *head = NULL;
BuildList(&head);
PrintList(head);

【讨论】:

  • 谢谢。这很有帮助。
【解决方案2】:

这里你需要发送指向列表 l 的指针地址作为参数而不是列表的地址,因为我们希望函数中所做的所有更改都影响列表 l,这只有在我们有列表的地址的情况下才能实现在函数中,这样对列表的任何更改都会在内存中永久更改!

所以你只需要使用

void BuildList(list **lreference)

在调用 BuildList 函数时,只需将指针的地址发送到列表。

list *l;
l = malloc(sizeof(list));
BuildFirst(&l);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-03
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    • 2011-12-02
    • 1970-01-01
    相关资源
    最近更新 更多