c - 链表-C-段错误

标签 c data-structures linked-list

我想弄清楚为什么我的程序在调用 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/

相关文章:

c - 如何从 C 中使用 MPI_Scatter 和 MPI_Gather?

algorithm - 删除所有不在任何路径上且 sum>= k 的节点

python - 按距离查找附近 xyz 点的最佳数据结构?

c - 在主程序中使用自定义 LinkedList 库;存储大小未知

c - 数据结构 - C 中的链表库

c++ - 使用常量内存将结构数组从主机复制到设备

c++ - 地址的奇怪错误

ios - 为基于 ARM 的设备优化 C 代码

c++ - 哪种数据结构更适合用于查找句子是否包含唯一字符?

c - 在C中的链表内添加元素到链表