C语言中函数数值传递问题
最近做一些题的时候,总是很疑惑一些问题,实在想不通了,希望知道的大虾,不吝赐教下
帮我看看我在代码中的注解,有空的话,帮我回答下,谢谢
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FAIL 0;
#define OK 1;
typedef struct Node{
int count;
char *word;
struct Node *lchild,*rchild;
}Node,*BitTree;
//BitTree 去定义一个变量时,那个变量就是一个指针变量吧,
//例如 BitTree bt; 效果等同 Node *bt吧
int SearchBS(BitTree root,char *keyword,BitTree *p)
{
BitTree pre;
*p=NULL;
pre=root;
while(pre)
{
if(strcmp(pre->word,keyword)==0)
{
*p=pre;
return OK;
}
else
{
*p=pre;
pre=(strcmp(pre->word,keyword)>0 ? pre->lchild : pre->rchild);
}
}
return FAIL;
}
//BitTree定义出来的变量就是个指针变量
//为什么还要定义成指向指针的指针变量呢?
//如果定义为int InsertBS(BitTree root,char *keyword)而不是下面这种
//不是可以通过地址传值吗,来改变Main中的root变量,何必还要用指向指针的指针变量了,实在想不通
//我也测试过了,如果定义为上面那种就出错.
int InsertBS(BitTree *root,char *keyword)
{
BitTree p,s;
if(SearchBS(*root,keyword,&p)==0)
{
s=(Node *)malloc(sizeof(Node));
if(!s) return FAIL;
s->word=(char *)malloc(strlen(keyword));
strcpy(s->word,keyword);
s->count=1;
s->lchild=NULL;
s->rchild=NULL;
if(p==NULL) *root=s;
else
{
if(strcmp(p->word,keyword)>0) p->lchild=s;
else
p->rchild=s;
}
}
else
p->count++;
return OK;
}
void InorderSort(BitTree root)
{
if(root==NULL) return;
InorderSort(root->lchild );
printf("%s(%d)",root->word,root->count);
InorderSort(root->rchild );
}
void main()
{
char ch,keyword[40]={0},buf[40]={0};
int i=0,tag=0;
BitTree root=NULL;
FILE *file;
file=fopen("in.txt","r");
if(!file) printf("Open file Failse!!!!");
while(!feof(file))
{
ch=fgetc(file);
if((ch>='a' && ch <='z')||(ch>='A' && ch <='Z'))
{
buf[i++]=ch;
tag=1;
}
else if(tag==1)
{
buf[i]='\0';
strcpy(keyword,buf);
strcpy(buf,"");
i=0;
tag=0;
if(InsertBS(&root,keyword)==0) return;
}
}
fclose(file);
InorderSort(root);
}
#include<stdio.h>void change(int &x,int &y){ int temp; temp=x; x=y; y=temp; printf("X:%d,Y:%d",x,y);}void main(){ int a=4,b=6; change(a,b); printf("a:%d,b:%d",a,b); getch();}
//BitTree定义出来的变量就是个指针变量//为什么还要定义成指向指针的指针变量呢?//如果定义为int InsertBS(BitTree root,char *keyword)而不是下面这种//不是可以通过地址传值吗,来改变Main中的root变量,何必还要用指向指针的指针变量了,实在想不通//我也测试过了,如果定义为上面那种就出错.因为在函数InsertBS(BitTree *root,char *keyword)中,s分配了地址,并且将s的地址赋值给了root,如果不用指向指针的指针,那么root的内容(也就是地址)是不能改变的,只是改变root的一个副本。所以要利用二维指针来修改地址。