为什么就是运行不出来
# include <stdio.h>
#define n 5
#define m 2*n-1
typedef struct{
float weight;
int parent,lchild,rchild;
}*hufmtree;
hufmtree tree[m];
void Hufmtree()
{
int i,j,p1,p2;
float small1,small2,f,maxval=10000.00;
int wpl=0;
printf("\n\t\t请输入%d棵树(叶子)的权值\nplease:\n\n",n);
for (i=0;i<m;i++)
{ tree[i]->parent=0;
tree[i]->lchild=0;
tree[i]->rchild=0;
tree[i]->weight=0.0;
}
for (i=0;i<n;i++)
{ printf("tree[%d].weight=",i);
scanf("%f",&f);
tree[i]->weight=f;
}
for (i=n;i<m;i++)
{ p1=0; p2=0;
small1=maxval; small2=maxval;
for (j=0;j<i-1;j++)
if (tree[j]->parent==0)
if (tree[j]->weight<small1)
{ small1= tree[j]->weight;
p2=p1; p1=j;
}
else
if (tree[j]->weight<small2)
{ small2=tree[j]->weight;
p2=j;
}
tree[p1]->parent=i+1;
tree[p2]->parent=i+1;
tree[i]->lchild=p1+1;
tree[i]->rchild=p2+1;
tree[i]->weight=tree[p1]->weight+ tree[p2]->weight;
}
printf("\n");
for(i=n;i<m;i++) { printf("tree[%d]->weight=%.2f\n",i,tree[i]->weight);}
printf("\n\tWPL=%.2f\n\n\t",tree[m-1]->weight);
}
void main()
{
Hufmtree();
}
[解决办法]
----------------修改后的代码-------------------------
#include <stdio.h>
#define n 5
#define m 2*n-1
typedef struct{
float weight;
int parent,lchild,rchild;
}hufmtree;
hufmtree tree[m];
void Hufmtree()
{
int i,j,p1,p2;
float small1,small2,f,maxval=10000.00;
int wpl=0;
printf("\n\t\t请输入%d棵树(叶子)的权值\nplease:\n\n",n);
for (i=0;i<m;i++)
{ tree[i].parent=0;
tree[i].lchild=0;
tree[i].rchild=0;
tree[i].weight=0.0;
}
for (i=0;i<n;i++)
{ printf("tree[%d].weight=",i);
scanf("%f",&f);
tree[i].weight=f;
}
for (i=n;i<m;i++)
{ p1=0; p2=0;
small1=maxval; small2=maxval;
for (j=0;j<i-1;j++)
if (tree[j].parent==0)
if (tree[j].weight<small1)
{ small1= tree[j].weight;
p2=p1; p1=j;
}
else
if (tree[j].weight<small2)
{ small2=tree[j].weight;
p2=j;
}
tree[p1].parent=i+1;
tree[p2].parent=i+1;
tree[i].lchild=p1+1;
tree[i].rchild=p2+1;
tree[i].weight=tree[p1].weight+ tree[p2].weight;
}
printf("\n");
for(i=n;i<m;i++) { printf("tree[%d].weight=%.2f\n",i,tree[i].weight);}
printf("\n\tWPL=%.2f\n\n\t",tree[m-1].weight);
}
void main()
{
Hufmtree();
}
[解决办法]
可以用的。只不过得先分配一下空间。
C++:
#include <iostream>using namespace std;//...typedef struct{ float weight; int parent,lchild,rchild;}huft, *hufmtree;//...void Hufmtree(){ int i,j,p1,p2; float small1,small2,f,maxval=10000.00; int wpl=0; printf("\n\t\t请输入%d棵树(叶子)的权值\nplease:\n\n",n); for (i=0;i<m;i++) tree[i] = new huft[m]; for (i=0;i<m;i++) { tree[i]->parent=0; tree[i]->lchild=0; tree[i]->rchild=0; //...
[解决办法]
定义的tree指针数组,其指针要先有指向,类似初始化。没指向一个结构体对象,又如何引用其成员变量。