链表打印分段错误

Linked list prints segmentation fault

我正在学习 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 仍然没有得到修改,即它仍然 NULL 然后当你做 head->base_priNULL->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--;
        }
}

嗨,看到你下面的错误:-

在下面的代码行中,您传递了 head 并且它的值为 NULL makeList(head, 15);

现在实际上你这样称呼它:-

makeList(NULL, 15);

而且它没有任何意义。哪个是错误的

像下面一样更正它并传递 head 的地址而不是值,即 NULL 地址

 makeList(&head, 15);

一旦像上面那样更正了函数调用,就必须像下面这样更改函数签名:-

您还需要像下面这样修改您的逻辑。在这里你实现了一个循环 link 列表。

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

还要打印列表,在主函数中修改如下代码:-

  IORB *temp = head;
  while(temp != NULL)
  {
      printf("%d\n", head->base_pri);
      temp = temp->link;
  }

我相信您要找的就是这个。我假设 int s 是您希望创建的链接列表的大小。你的 makeList(IORB *h, int s) 应该看起来更像这样,(如果你想避免双指针)

在您的 main 中,您可以创建一个头节点,例如:head = (IORB*) malloc(sizeof(IORB)); 然后调用您的 makeList(head, 15);

你的 makeList 函数看起来像这样:

IORB* temp = h; //set temp to head (since we made sure head is not NULL)

while(s > 0){
    temp->link = (IORB*)malloc(sizeof(IORB)); //create it's next node
    temp->link->base_pri = (rand() % 20);
    temp = temp->link; //remember to move temp pointer to the newly created node
    s--;    
}