链表因段错误无法显示,程序未进入createList函数求助
问题根源与修复方案
核心错误
你代码里的全局指针head初始化为NULL,但在createList函数第一行直接写head->data = arr[0];——空指针解引用会直接触发段错误,程序还没走到for循环就崩溃了,自然看不到printf的输出。
修复步骤
- 给头节点分配内存:在使用
head之前,必须先用malloc为它申请空间 - (可选)避免全局指针:全局变量容易引发这类隐蔽错误,改成局部指针更安全
修复后的完整代码
#include<stdio.h> #include<stdlib.h> struct Node{ int data; struct Node *next; }; struct Node * createList( int arr[], int n){ // 先为头节点分配内存 struct Node *head = (struct Node *)malloc(sizeof(struct Node)); head->data = arr[0]; head->next = NULL; struct Node * last = head; for(int i=1; i<n; i++){ struct Node *newNode = (struct Node *)malloc(sizeof(struct Node)); newNode->data = arr[i]; newNode->next = NULL; last->next = newNode; last = newNode; printf("executed "); } return head; } void Display(struct Node * head){ struct Node * p = head; while(p!=NULL){ printf("%d ", p->data); p = p->next; } } int main() { int arr[]={2,55,2,6,66}; struct Node * result = createList(arr, 5); Display(result); return 0; }
额外说明
- 移除了无用的
#include<conio.h>,这个头文件属于DOS时代遗留,现代编译器基本不需要 - 将全局
head改为createList内的局部变量,减少全局变量带来的意外问题 - 修复后程序会正常执行,输出
executed executed executed executed 2 55 2 6 66
内容的提问来源于stack exchange,提问作者Ashwin Gorle
相关产品推荐
相关产品推荐

