帮我看看这个二叉树程序为啥会出现段错误...
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了帮我看看这个二叉树程序为啥会出现段错误...相关的知识,希望对你有一定的参考价值。
是一个二叉树遍历的程序,输入为in.txt,输出为三个文件pre.txt mid.txt aft.txt,文件是创建好的而且属性已经改好,编译没问题,为什么一执行就出毛病...
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
typedef struct node
char data;
struct node *lchild, *rchild;
treenode;
#define treenodelen sizeof(treenode)
treenode *tree;
treenode *createtree(treenode *tree)
FILE *fp1;
char ch;
fp1=fopen("in.txt","r");
ch=fgetc(fp1);
if (ch=='*') tree=NULL;
else
tree = (treenode *)malloc(treenodelen);
tree->data = ch;
tree->lchild=createtree(tree->lchild);
tree->rchild=createtree(tree->rchild);
fclose(fp1);
return(tree);
void pre(treenode *tree)
FILE *fp2;
fp2=fopen("pre.txt","w");
if (tree==NULL) return;
else
fputc(tree->data,fp2);
pre(tree->lchild);
pre(tree->rchild);
fclose(fp2);
void mid(treenode *tree)
FILE *fp3;
fp3=fopen("mid.txt","w");
if (tree==NULL) return;
else
mid(tree->lchild);
fputc(tree->data,fp3);
mid(tree->rchild);
fclose(fp3);
void aft(treenode *tree)
FILE *fp4;
fp4=fopen("aft.txt","w");
if (tree==NULL) return;
else
aft(tree->lchild);
aft(tree->rchild);
fputc(tree->data,fp4);
fclose(fp4);
int main()
tree=createtree(tree);
if (tree)
pre(tree);
mid(tree);
aft(tree);
return 0;
所要做的,就是把fopen放到递归外层。
我把createtree改写了一下,增加了一个建立结点的函数:
treenode *create_node(treenode *tree,FILE *fp)
char ch;
if((int)(ch=fgetc(fp))==EOF)
return 0;
tree = (treenode *)malloc(treenodelen);
tree->data = ch;
tree->lchild=create_node(tree->lchild,fp);
tree->rchild=create_node(tree->rchild,fp);
return (tree);
treenode *createtree(treenode *tree)
FILE *fp1;
fp1=fopen("c:\\tmp\\in.txt","r");
tree=create_node(tree,fp1);
fclose(fp1);
return(tree);
输出函数,你可以依次更改:pre(tree); mid(tree); aft(tree);本回答被提问者采纳
以上是关于帮我看看这个二叉树程序为啥会出现段错误...的主要内容,如果未能解决你的问题,请参考以下文章
为啥这个基本链表可以在 MacOS 上工作,但在 Linux 上会出现段错误
为啥这段代码在 64 位架构上会出现段错误,但在 32 位上却能正常工作?