调试时,它告诉我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;
}
构建清单的辅助功能:
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。最终,它的起源是构建清单中的动态分配。来自主要的呼叫是:
list *head = NULL;
BuildList(&head);
PrintList(head);
替换printlist(头)时;使用PrintList(& head);它打印一个空列表,而不会失败。
您将指针传递给功能:
buildList(list *l)
这意味着当您在功能内部分配它时,您将不会在此功能之外使用此指针,因为它在堆栈中。您可以做的是,分配此功能之外的列表,例如:
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);
在这里,您需要将指针的地址发送到列表l作为争论而不是列表地址,因为我们希望函数中完成的所有更改都会影响列表l,只能实现这一点如果我们在函数中具有列表的地址,以便在内存中永久更改列表的任何更改!
所以你只需要使用
void BuildList(list **lreference)
,只需在调用build lastist函数时将指针的地址发送到列表。
list *l;
l = malloc(sizeof(list));
BuildFirst(&l);