C语言链表打印head的base_pri出现段错误求助
嘿,我来帮你搞定这个段错误的问题!
核心问题:值传递导致全局指针head没被正确修改
你代码里的makeList(head, 15);是把全局变量head的当前值(NULL)传递给函数参数h。但C语言是值传递——函数里的h只是head的一个副本,你在makeList里修改h的指向,完全不会影响外面的全局head。
结果就是main里的head始终是NULL,你去访问head->base_pri相当于解引用空指针,直接触发段错误。
两种修复方案
方案1:让makeList返回新的头指针
把链表的头指针作为函数返回值,在main里赋值给全局head:
#include<stdlib.h> #include<stdio.h> // 别忘了加这个,printf依赖它 #include<time.h> // 用来初始化随机数 typedef struct iorb { int base_pri; struct iorb *link; } IORB; IORB *head = NULL; // 修改函数声明,返回IORB*类型 IORB* makeList(int s); int main(){ srand(time(NULL)); // 初始化随机数种子,避免每次生成相同序列 head = makeList(15); if(head != NULL){ // 加个判断,防止malloc失败导致空指针 printf("%d\n", head->base_pri); } return 0; } IORB* makeList(int s){ IORB *h = NULL; IORB *tail = NULL; // 用尾指针避免每次遍历找链表末尾 while(s > 0){ IORB *temp = (IORB*)malloc(sizeof(IORB)); if(temp == NULL){ // 必须检查malloc是否成功 // 这里可以加错误处理,比如释放已分配的内存 return h; } temp->base_pri = (rand() % 20); temp->link = NULL; // 新节点的link必须设为NULL,避免野指针 if(h == NULL){ h = temp; tail = temp; } else { tail->link = temp; tail = temp; } s--; } return h; }
方案2:传递指针的指针(IORB**)
通过传递head的地址,让函数直接修改全局指针的指向:
#include<stdlib.h> #include<stdio.h> #include<time.h> typedef struct iorb { int base_pri; struct iorb *link; } IORB; IORB *head = NULL; // 参数改为IORB**,接收指针的地址 void makeList(IORB **h, int s); int main(){ srand(time(NULL)); makeList(&head, 15); // 传head的地址 if(head != NULL){ printf("%d\n", head->base_pri); } return 0; } void makeList(IORB **h, int s){ *h = NULL; IORB *tail = NULL; while(s > 0){ IORB *temp = (IORB*)malloc(sizeof(IORB)); if(temp == NULL){ return; } temp->base_pri = (rand() % 20); temp->link = NULL; if(*h == NULL){ *h = temp; tail = temp; } else { tail->link = temp; tail = temp; } s--; } }
额外注意点
- 一定要包含
stdio.h,否则printf会有未定义行为; malloc后必须检查返回值,避免内存分配失败导致的空指针;- 新节点的
link要设为NULL,不然链表末尾会是野指针,后续遍历会出问题; - 初始化
rand的种子(srand(time(NULL))),不然每次运行程序生成的随机数序列都一样。
内容的提问来源于stack exchange,提问作者b.gaz
相关产品推荐
相关产品推荐

