我正在学习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/