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

C语言线性数据结构递归查找节点遇段错误及指针赋值问题求助

C语言链表递归查找函数的段错误与指针赋值问题修复

段错误原因分析

你在main函数中声明了TypeLDS *out = NULL;,并将这个NULL指针传入findPosLDS函数。当函数中执行*out = input;时,实际上是在对NULL指针进行解引用操作,这直接触发了segmentation fault(段错误)——因为NULL指针指向的内存区域是不可访问的。

指针赋值无法在main生效的问题根源

你之前尝试的out = &input操作无效,原因有两点:

  1. input是findPosLDS函数的局部形参,它的地址是栈上的临时地址,函数执行完毕后该地址会被释放,即使赋值给out也没有意义。
  2. out本身是函数的形参(二级指针),直接修改out的值只是修改了形参的副本,不会影响main函数中原始的out变量。正确的做法是通过解引用out,修改它指向的内存区域的值。

修复后的完整代码

#include <stdio.h>
#include <stdlib.h>

// 链表结构体定义
typedef int InfoTypeLDS;
struct elemLDS{
    InfoTypeLDS info;
    struct elemLDS* next;
};
typedef struct elemLDS NodeTypeLDS;
typedef NodeTypeLDS* TypeLDS;

TypeLDS createNode();
void addHeadNotRand(TypeLDS* lds, InfoTypeLDS elem);
void findPosLDS(TypeLDS input, InfoTypeLDS req, TypeLDS *out);
void printf_LDS(TypeLDS in);

int main(){
    TypeLDS head = createNode();
    addHeadNotRand(&head, 3);
    addHeadNotRand(&head, 1);
    addHeadNotRand(&head, 65);
    addHeadNotRand(&head, 34);
    addHeadNotRand(&head, 2);
    
    // 修正:声明一个TypeLDS变量存储找到的节点地址,传入它的地址
    TypeLDS out = NULL;
    printf_LDS(head);
    findPosLDS(head, 65, &out);
    
    if(out != NULL){
        printf("找到节点地址: %p, 值: %d\n", out, out->info);
    } else {
        printf("未找到目标节点\n");
    }
    return 0;
}

TypeLDS createNode(){
    TypeLDS out = (TypeLDS) malloc (sizeof(NodeTypeLDS));
    out -> next = NULL;
    return out;
}

void addHeadNotRand(TypeLDS* lds, InfoTypeLDS elem){
    TypeLDS temp = *lds;
    *lds = (TypeLDS) malloc (sizeof(NodeTypeLDS));
    (*lds) -> info = elem;
    (*lds) -> next = temp;
}

void findPosLDS(TypeLDS input, InfoTypeLDS req, TypeLDS *out){
    // 新增:检查input是否为NULL,避免遍历空指针时解引用出错
    if(input == NULL){
        *out = NULL;
        return;
    }
    
    if (input -> info == req){
        *out = input;
        printf("函数内找到节点地址: %p, 值: %d\n", input, input -> info);
        return;
    }
    // 移除冗余的next判断,递归到input为NULL时统一处理
    findPosLDS(input -> next, req, out);
}

void printf_LDS(TypeLDS in){
    if (in == NULL || in -> next == NULL){
        printf("\n");
        return;
    }
    printf("%2d ", in -> info);
    printf_LDS(in -> next);
}

关键修改点

  • main函数:将TypeLDS *out = NULL;改为TypeLDS out = NULL;,调用findPosLDS时传入&out,让函数能直接修改main中out变量的值。
  • findPosLDS函数:新增input == NULL的判断,避免递归到空指针时触发额外的段错误;简化逻辑,移除冗余的input->next == NULL判断。
  • printf_LDS函数:新增in == NULL的判断,防止传入空链表时出错。

内容的提问来源于stack exchange,提问作者prollyyes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 15:15:21