为什么C语言里用指针当做形参还是无法返回给实参数据啊?
前面的代码分别是哈夫曼表的创建、挑选、打印函数:
void CreatHuffmanTree(HuffmanTree HT,int n,int w[]);
void select(HuffmanTree HT, int n, int &s1, int &s2);
void printHuffmanTree(HuffmanTree HT, char ch[]);
然后就是int main(),问题就出在这里面。
printHuffmanTree函数我将之放在main里无法使用,但是放在哈夫曼创建的那个函数定义里就可以。
我想问明明传给创建函数的是 HT的指针格式,可是还是不能返回HT表格数据到main里。。。求大神解惑,小白初学者。。
#include<stdio.h>
#include<malloc.h>
int num=8;
using namespace std;
typedef struct{
int weight;
int parent,lch,rch;
}HTNode,*HuffmanTree;
void CreatHuffmanTree(HuffmanTree HT,int n,int w[]);
void select(HuffmanTree HT, int n, int &s1, int &s2);
void printHuffmanTree(HuffmanTree HT, char ch[]);
//打印哈夫曼满树
void printHuffmanTree(HuffmanTree HT)
{
printf("\n");
printf("weight, parent, lchild, rchild\n");
for(int i = 1; i <= 2*num-1; i++){
if(i > num){
printf("%5d, %5d, %5d, %5d\n", HT[i].weight, HT[i].parent, HT[i].lch, HT[i].rch);
}else{
printf("%5d, %5d, %5d, %5d\n", HT[i].weight, HT[i].parent, HT[i].lch, HT[i].rch);
}
}
printf("\n");
}
void select(HuffmanTree HT, int n, int &s1, int &s2)
{
//假设s1对应的权值总是<=s2对应的权值
int min=100000,min_i=0;//求s1.
for(int i=1;i<=n;i++)
{
if(HT[i].parent==0)
{
if(min>HT[i].weight)
{
min=HT[i].weight;
min_i=i;
}
}
}
s1=min_i;
min=100000,min_i=0;//求s2.
for(int i=1;i<=n;i++)
{
if(HT[i].parent==0&&i!=s1)
{
if(min>HT[i].weight)
{
min=HT[i].weight;
min_i=i;
}
}
}
s2=min_i;
printf("%d--%d\n",HT[s1].weight,HT[s2].weight);
}
void CreatHuffmanTree(HuffmanTree HT,int num,int w[])
{
if(num<=1)return;
int m=2*num-1;//数组共2n-1个元素。
HT=(HuffmanTree)malloc(sizeof(HTNode)*(m+1)) ;//开辟空间……
if(!HT){printf("错误\n");return;}//判断开辟空间是否成功……
for(int i=1;i<=num;i++)
{
HT[i].lch=0;
HT[i].rch=0;
HT[i].parent=0;
HT[i].weight=w[i];
}
for(int i=num+1;i<=m;i++)
{
HT[i].lch=0;
HT[i].rch=0;
HT[i].parent=0;
HT[i].weight=0;
}
for(int i = num+1; i <= m; i++){
int s1, s2;
select(HT, i-1, s1, s2);//在HT[1...i-1]里选择parent为0的且权值最小的2结点,其序号分别为s1,s2,parent不为0说明该结点已经参与构造了,故不许再考虑
HT[s1].parent = i;
HT[s2].parent = i;
HT[i].lch = s1;
HT[i].rch = s2;
HT[i].weight = HT[s1].weight + HT[s2].weight;
}
printHuffmanTree(HT);////这个句子放在下面main里就不能用,只能放这里。。///////
}
int main(){
int w[9]={000,7,19,2,6,32,3,21,10} ;
HuffmanTree HT;
CreatHuffmanTree(HT,num,w);
return 0;
}