关于树的头结点指针和头结点指针的指针作参数的问题
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
而第二个程序输出的则不同,即不是头结点的地址。