c - 链表打印段错误

标签 c linked-list singly-linked-list

我正在学习c中的链表,当我尝试在main()中打印头部的base_pri时,它只会给我一个段错误。 这是我的代码:

#include<stdlib.h>

typedef struct iorb {
int base_pri;
struct iorb *link;
} IORB;

IORB *head = NULL;
void makeList(IORB *h, int s);

int main(){
  makeList(head, 15);

  printf("%d\n", head->base_pri);

    return 0;
}

 void makeList(IORB *h, int s){
      while(s > 0){
        IORB *temp = (IORB*)malloc(sizeof(IORB));
        temp->base_pri = (rand() % 20);
        temp->link = h;
        h = temp;
        s--;
    }
 }

如有任何建议,我们将不胜感激。

最佳答案

您将 head 作为按值调用传递给 makeList(),当控制返回到调用函数 head 时仍然没有get修改,即它仍然是NULL,接下来当你执行head->base_pri时,即NULL->base_pri显然它给出了seg。错误。

而不是将 head 传递给 makeList(),而是将 head 的地址传递为

typedef struct iorb {
        int base_pri;
        struct iorb *link;
} IORB;
IORB *head = NULL;
void makeList(IORB **h, int s);
int main(){
        makeList(&head, 15);/* pass head address */
        printf("%d\n", head->base_pri);
        return 0;
}
void makeList(IORB **h, int s){
        while(s > 0){
                IORB *temp = (IORB*)malloc(sizeof(IORB));
                temp->base_pri = (rand() % 20);
                temp->link = (*h);
                (*h) = temp;
                s--;
        }
}

关于c - 链表打印段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49880034/

相关文章:

c++ - 方法超出范围后是否应该删除引用的 std::shared_ptr ?

c++ - 如何在 PC/Visual C++ 上查明指针是否在堆栈上

c - 如何遍历多级链表?

c++ - 将节点附加到链表时出现段错误

c - 链表 append 实现在 C 中更新所有节点值

c - 对单向链表进行排序 - 我不明白

c++ - 提高从数组向链表插入元素的性能

c - RGB原始图像的简单模糊

c - "overload"c 中的函数 - 不知道输入参数类型

c - 非阻塞读永不返回