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

K&R习题6.3:树遍历函数循环内正常但循环外异常问题排查

K&R《C程序设计语言》习题6.3交叉引用程序节点丢失问题排查

问题描述

正在完成K&R《C程序设计语言》习题6.3,编写交叉引用程序输出文档中所有单词及其出现行号(暂未实现冗余词去除)。遇到异常:displaytree二叉树遍历函数在getword的while循环内调用时,可完整输出所有节点;移至循环结束后调用,仅输出部分节点(如输入指定文本后,仅输出(cat)(is)(on)(pen))。

问题根源:结构体指针类型定义错误

在lnode和tnode结构体定义中,成员指针未添加struct关键字,导致编译器无法识别正确的指针类型,二叉树的左右子树指针被错误存储,最终遍历无法访问到右子树的节点(如table、the、under)。

错误定义

struct lnode {
    int linen;
    lnode *next;  // 缺少struct关键字
};

struct tnode {
    char *value;
    tnode *left;  // 缺少struct关键字
    tnode *right;
    lnode *lines;
};

修正后的正确定义

struct lnode {
    int linen;
    struct lnode *next;
};

struct tnode {
    char *value;
    struct tnode *left;
    struct tnode *right;
    struct lnode *lines;
};

补充说明

在C语言中,若未对结构体进行typedef声明,直接使用结构体名(如lnode、tnode)作为指针类型时,编译器无法识别,会导致指针类型不匹配、内存访问错误。这会使得二叉树的右子树节点无法被正确挂载和遍历,从而出现循环内(节点逐步添加时)能临时访问到完整结构,但循环结束后遍历丢失部分节点的异常。

修正后,循环外调用displaytree将正确输出所有节点:

(cat)(is)(on)(pen)(table)(the)(under)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 21:54:52