指针与指向指针的指针
typedef int ElemType;
typedef struct Binary_Tree{
ElemType value;
int bf ;
struct Binary_Tree *lchild,*rchild;
}Tree;
void InsertTree(Tree **t,ElemType e){
Tree *node;
node=*t;
if(!node){
node=(Tree *)malloc(sizeof(Tree));
node->value=e;
node->lchild=NULL;
node->rchild=NULL;
*t=node;
}
else if(e<((*t)->value)){
InsertTree(&((*t)->lchild),e);
}
else if(e>((*t)->value)){
InsertTree(&((*t)->rchild),e);
}
}
void firstPrint(Tree *t){
if(t){
printf("%i \n",t->value);
firstPrint(t->lchild);
firstPrint(t->rchild);
}
}
int HeightTree(Tree *t){
if(!t)
return 0;
int h1=HeightTree(t->lchild);
int h2=HeightTree(t->rchild);
return h1>h2?(h1+1):(h2+1);
}
int main(void){
Tree *MyTree=NULL;
InsertTree(&MyTree,5);
InsertTree(&MyTree,8);
InsertTree(&MyTree,6);
firstPrint(MyTree);
printf("Height of Tree is %i \n",HeightTree(MyTree));
}
在mian中使用了指向指针的指针,开始时为InsertTree(MyTree,5);但是发现在函数运行结束时MyTree仍为空。下面来分析原因:
在函数参数中传递变量和变量的地址的效果不同
int a=9;
void changeValue(int i){ i=6;}
运行changeValue(a)的结果后,a的值还是9.
void changeValueAddre(int &i){i=6;}
运行changeValueAddre(a)后,a的值为6,发生改变。
因为函数从其参数中接受数据时,都是接受其的副本,存在堆栈中,在函数运行时改变的是副本的值,所以不会改变原始值。当传入的是地址时,同样把地址的副本
存入堆栈,但是不管是原来的地址,还是堆栈中的副本,它们都指向内存中的同一地方,所以值会改变。
同理,InsertTree(MyTree,5);开始时MyTree是一个跟节点,值为空。堆栈存入其副本后,为其分配空间。但是原始值和分配的空间没有任何指向,所以仍为空。
当InsertTree(&MyTree,5)时,MyTree为null,但是&MyTree中存放的是MyTree的地址,并把该地址拷贝到堆栈中。该拷贝指向的内存就是MyTree的地址
Tree *node;
node=(Tree *)malloc(sizeof(Tree)); //为node分配内存空间,并指向该空间。
*t=node; // 为内存空间中的MyTree赋值。
浙公网安备 33010602011771号