You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

链表因段错误无法显示,程序未进入createList函数求助

问题根源与修复方案

核心错误

你代码里的全局指针head初始化为NULL,但在createList函数第一行直接写head->data = arr[0];——空指针解引用会直接触发段错误,程序还没走到for循环就崩溃了,自然看不到printf的输出。

修复步骤

  1. 给头节点分配内存:在使用head之前,必须先用malloc为它申请空间
  2. (可选)避免全局指针:全局变量容易引发这类隐蔽错误,改成局部指针更安全

修复后的完整代码

#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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 09:22:07