头节点和头指针用c语言定义,关于树的头结点指针和头结点指针的指针作参数的有关问题...

关于树的头结点指针和头结点指针的指针作参数的问题

C/C++ code#include "stdio.h"

#include "conio.h"

#define Status int

typedef struct BNode{

int data;

struct BNode *lchild,*rchild;

}BNode,*BiTree;

Status CreateBitree(BiTree *T)

{

char ch;

fflush(stdin);

scanf("%c",&ch);

if(ch=='#')

(*T)=NULL;

else{

(*T)=(BNode *)malloc(sizeof(BNode));

if(T==NULL) return 0;

(*T)->data=ch;

CreateBitree(&((*T)->lchild));

CreateBitree(&((*T)->rchild));

}

return 1;

}

void printBitree(BiTree T)

{

if(T!=NULL){

printf("%c",T->data);

printBitree(T->lchild);

printBitree(T->rchild);

}

}

main()

{

BiTree b;

CreateBitree(&b);

printBitree(b);

getch();

}

下面这个为什么就不能输出,还有两者的区别

C/C++ code#include "stdio.h"

#include "conio.h"

#define Status int

typedef struct BNode{

int data;

struct BNode *lchild,*rchild;

}BNode,*BiTree;

Status CreateBitree(BiTree T)

{

char ch;

fflush(stdin);

scanf("%c",&ch);

if(ch=='#')

T=NULL;

else{

T=(BNode *)malloc(sizeof(BNode));

if(T==NULL) return 0;

T->data=ch;

CreateBitree(T->lchild);

CreateBitree(T->rchild);

}

return 1;

}

void printBitree(BiTree T)

{

if(T!=NULL){

printf("%c",T->data);

printBitree(T->lchild);

printBitree(T->rchild);

}

}

main()

{

BiTree b;

CreateBitree(b);

printBitree(b);

getch();

}

------解决方案--------------------

在局部函数里某个外部值而有效,我们一般是传递的这个数据的指针给局部函数,上面的道理和这是一样的。你在创建树的函数里需要修改的是指针的值,所以我们要传递的是指针的指针。而你第二个没有传递指针的指针,在局部函数里面做了修改,但是当局部函数返回后就无效了,也就是你的创建工作没有完成,所以输出是没有效的了。

看下我的这篇帖子。

http://topic.csdn.net/u/20120319/15/0751ad00-bad3-481b-9f3a-fed7409cb9cc.html

------解决方案--------------------

修改参数

------解决方案--------------------

而BiTree是指向BNode的指针,那么我用BiTree作参数,拷贝的应该是头结点BNode的地址

---------------------------------

当你用BiTree作参数,拷贝的并不是头结点BNode的地址,只是 BiTree b

的一个拷贝。有一个很简单实用的方法是输出BiTree的地址,看BiTree的地址是

如何变化的。如第一个程序中在main的BiTree b;后面加上一条语句printf("%p\n",&b);

在Status CreateBitree(BiTree *T)中的if(T==NULL) return 0;后面

加上printf("%p\n",&(*T));把代码跑起来会看到CreateBitree

输出的地址与main中是一样的,如:

0012FF7C

1

0012FF7C

2

00431DD4

#

#

3

00431DD8

#

#

123Press any key to continue

而第二个程序输出的则不同,即不是头结点的地址。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值