【发布时间】: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