gpt4 book ai didi

c - 链表函数返回中的指针问题我无法理解

转载 作者:太空宇宙 更新时间:2023-11-04 08:08:29 25 4
gpt4 key购买 nike

调试时,它告诉我 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);用 PrintList(&head);它打印一个空列表,没有失败。

最佳答案

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

BuildList(list *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);

关于c - 链表函数返回中的指针问题我无法理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41075870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com