Directory
一、数组中的指针
先看整型指针的使用,在change函数中无需引用传递指针,但是定义整型指针以后需要对其进行初始化(i=&j)
#include<stdio.h>
void change(int *i){
(*i)=200;
}
int main(){
int j=9;
int *i;
i=&j;
(*i)=100;
change(i);
printf("%d",*i);
return 0;
}
在函数中,传入指向数组0位置指针(数组名),数组指针指向数组内容。无需引用传递就可以修改原数组的值。(在定义数组以后,数组名指针已经被初始化,有明确的指向)
#include<stdio.h>
void update(char a[]){
char *p;
p=a;
while((*p)!='\0'){
(*p)='h';
p++;
}
}
int main(){
char a[]="Hello,HowCowBear!";
update(a);
printf("%s",a);
}
二、树中的指针——以排序二叉树为例
#include <stdio.h>
#include <stdlib.h>
typedef int Status;
typedef int ElemType;
#define OK 1
#define OVERFLOW -2
//定义树节点
typedef struct BiTNode {
ElemType data;
struct BiTNode *lchild, *rchild;
} BiTNode, *BiTree;
//创建树
Status CreateBiTree(BiTree &T,int x){
if(T==NULL){
T=(BiTree)malloc(sizeof(BiTNode));
T->data=x;
T->lchild=NULL;
T->rchild=NULL;
return OK;
}
else if(x<(T->data)){
CreateBiTree(T->lchild,x);
}
else{
CreateBiTree(T->rchild,x);
}
}
在创建树的函数中,形参传入已经是指针Bitree,但是需要引用传递(&),否则就无法改变原树的值(编译会成功,调试时出现内存错误)。
使用整型指针时,定义指针后需要对其进行初始化(i=&j)以后即可使用,然而树节点的指针没有初始化,没有分配内存空间,没有明确的指向,在函数中无法正确地传入一个正确的地址。因此需要引用传递,才能引用到“未初始化的指针”并对其分配内存空间,从而进行操作。引用传递相当于传入树节点指针的指针(树节点的指针没有明确指向,但是树节点指针的指针有明确的地址,这个地址指向该树节点指针。)
给出整型指针和树节点指针的例子(整型指针和树节点指针都没有初始化,打印他们所指向的地址):
#include<stdio.h>
typedef struct BiTNode{
char date;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
int main(){
BiTree T1; // 未进行初始化的树结点指针
BiTree T2;
int *i; //未进行初始化的整型指针
printf("%d\n",T1);
printf("%d\n",T2);
printf("%d",i);
}
运行结果
三、给出排序二叉树的全部代码
#include <stdio.h>
#include <stdlib.h>
typedef int Status;
typedef int ElemType;
#define OK 1
#define OVERFLOW -2
int depth[10001];
int degree[10001];
int num=0;
int num1=0;
int alldepth;
//定义树节点
typedef struct BiTNode {
ElemType data;
struct BiTNode *lchild, *rchild;
} BiTNode, *BiTree;
//初始化
void Init(BiTree &T){
T=NULL;
}
int DeepTree(BiTree T)
{
if(T == NULL)
return 0;
int ldeep, rdeep, deep = 0;
ldeep=DeepTree(T->lchild);
rdeep=DeepTree(T->rchild);
deep = (ldeep > rdeep ? ldeep : rdeep);
return (deep + 1);
}
//
Status CreateBiTree(BiTree &T,int x){
if(T==NULL){
T=(BiTree)malloc(sizeof(BiTNode));
T->data=x;
T->lchild=NULL;
T->rchild=NULL;
return OK;
}
else if(x<(T->data)){
CreateBiTree(T->lchild,x);
}
else{
CreateBiTree(T->rchild,x);
}
}
void allTree(BiTree T){
if(T==NULL) return;
allTree(T->lchild);
printf("%d ",T->data);
if((T->lchild)!=NULL){
degree[num1]++;
}
if((T->rchild)!=NULL){
degree[num1]++;
}
depth[num]=alldepth-DeepTree(T);
num++;
num1++;
allTree(T->rchild);
}
int main()
{
BiTree T;
Init(T);
int n;
int x;
scanf("%d",&n);
for(int i=0;i<n-1;i++){
scanf("%d ",&x);
CreateBiTree(T,x);
}
alldepth=DeepTree(T);
scanf("%d",&x);
CreateBiTree(T,x);
allTree(T);
printf("\n");
for(int i=0;i<num;i++){
printf("%d ",depth[i]);
}
printf("\n");
for(int j=0;j<num1;j++){
printf("%d ",degree[j]);
}
return 0;
}