您的位置:首页 > 其它

寻找到大Bug一只

2013-12-01 16:52 225 查看
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10000
int count;
typedef struct node
{
    int weight;
    int data;
    int parent,lchild,rchild;
}Node;
Node huffmanNode[260];

int find(int value)
{
    int i = 1;
    for(;i<=count;i++)
    {
        if(huffmanNode[i].data == value)
        {
            return i;
        }
    }
    return 0;
}
//获取文件以及获得词频
void  calWeight()
{
    count = 0;
    FILE *f;
    int a;
    f = fopen("goal.txt","rb");
    if(f == NULL)
    {
        printf("文件不存在!打开失败!");
        return ;
    }
    while(!feof(f))
    {
        a = fgetc(f);

        if(!find(a))
        {
            count++;
            huffmanNode[count].weight = 1;
            huffmanNode[count].data   = a;
        }
        else
        {
            huffmanNode[find(a)].weight++;
        }
    }

}

//建立huffman树 根据huffman树的特性,具有n个节点的huffman树的具有2n-1个节点
void  createHufmanTree(Node * huffmanTree)
{
    int m = 2*count - 1;
    int m1,m2,x1,x2,i,j;
    huffmanTree = (Node *)malloc(m*sizeof(Node));
    //初始化结点信息
    for(i=1;i<=count;i++)
    {

        huffmanTree[i].data = huffmanNode[i].data;
        huffmanTree[i].lchild = -1;
        huffmanTree[i].rchild = -1;
        huffmanTree[i].parent = -1;
        huffmanTree[i].weight = huffmanNode[i].weight;
    }
    for(;i<=m;i++)
    {
        huffmanTree[i].data = 0;    huffmanTree[i].weight = 0;
        huffmanTree[i].lchild = -1; huffmanTree[i].rchild = -1;
        huffmanTree[i].parent = -1;
    }

}

/*字符编码*/
char * getHuffmanCode(Node * huffmanTree)
{
    char * cd = (char *)malloc((count+1)*sizeof(char));
    cd[count+1] = '\0';
}
void test()
{
    int i = 1;
    for(;i<=count;i++)
    {
        printf("huffmanNode[%d].data = %d  huffmanNode[%d].weight = %d\n",i,huffmanNode[i].data,i,huffmanNode[i].weight);
    }
}
int main()
{
    calWeight();
    printf("%d \n",count);
    test();
    Node *huffmanTree;
    createHufmanTree(huffmanTree);
    return 0;
}


以上代码在createHuffmanTree函数里面有个错误,找找看。

发现有两个错误,其实很严重的样子

Node *huffmanTree = (Node *)malloc((2*count-1+1)*sizeof(Node));

createHufmanTree(huffmanTree);

这样才对
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: