I am trying to make a huffman coding program. As the first step I'm trying to list the letters in a given paragraph and the amount of the letters. I don't know my logic is right or not but I'm getting a realloc error. I couldn't figure out why. Here is my code:
#include <stdio.h>
#include <stdlib.h>
#define fpath1 "reference.txt"
typedef struct huffman{
char x;
int xnum;
struct huffman *left;
struct huffman *right;
}huff;
void HuffmanTree();
void main(void){
HuffmanTree();
}
void HuffmanTree(){
huff *tree;
int i=0,j,k,flag=0;
char *x;
FILE *fp;
fp=fopen(fpath1,"r");
x=(char*)malloc(sizeof(char));
tree=(huff*)malloc(sizeof(huff));
while(!feof(fp)){
fscanf(fp,"%c",&x[i]);
x=(char *)realloc(x,(i+2)*sizeof(char));
i++;
printf("%d-",i); //test.
}
for(j=0;j<i;j++){
tree[j].xnum=1;
for(k=0;k<j;k++){
if(tree[j].x==x[k]){ //if there is a character x[i] in tree[j] before.
flag=1;
tree[j].xnum++;
tree=(huff*)realloc(tree,(j+2)*sizeof(huff));
k=j;
}
}
if(flag==0) tree[j].x=x[k];
flag=0;
}
for(i=0;i<100;i++) printf("%c %d\n",tree[i].x,tree[i].xnum);
}