我想弄清楚为什么我的程序在调用 ll_print 时崩溃了。 [[这是一个非常简单直接的问题,我不确定要添加什么才能真正填补解释空白]]
struct ll{
struct ll* next;
int n;
} ll;
void ll_print(struct ll *l){
while (l) {
printf("%d ", l->n);
l=l->next;
}
}
void ll_fill(struct ll *l, int n){
struct ll *temp= NULL;
while (n>0){
l= (struct ll*)malloc(sizeof(struct ll));
l->n=n;
l->next= temp;
temp=l;
n--;
}
}
int main(void){
int i=0;
struct ll *l;
ll_fill(l, 10);
ll_print(l); /** causing a segmntation fault **/
}
最佳答案
发生这种情况是因为 l
指针永远不会被初始化。看来你期待 ll_fill
初始化它,但你错了 - 它正在按值传递(读取 - 通过复制),以及你分配给 l
的任何内容在 ll_fill
函数没有给 l
赋值内部声明 main
.要实现你想要的,通过 l
通过指针(你将有指向指针的指针)。或者,将其设为 ll_fill
的返回值并做 l = ll_fill(l, 10);
.另外,给自己一个调试器——它会对你有很大帮助。
关于c - 链表-C-段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11489896/