I'm trying to make a huffman coder.. but I'm having some problems...
This is how I define my structure of a node..
struct node{
int type,prob;
char *code;
struct node *left, *right;
};
I order by probabilities and I create a new node
struct node join_nodes(struct node no1, struct node no2)
{
struct node aux;
aux.type = 1;
aux.prob = no1.prob + no2.prob;
aux.right = &no1;
aux.left = &no2;
return aux;
}
Then I put this new node in the list of nodes..
void sort_hufman(struct node order_list[], struct node list[])
{
int i = N, len = N;
struct node aux;
for(i=N; i>N-2;i--)
{
sort(order_list, i);
len = len +1;
aux = join_nodes(order_list[i-1],order_list[i-2]);
list[len-1] = order_list[i-2] = aux;
}
}
The thing is that in this fuctions my first subnode types are 0 and 0 that this means that they are leafs but wen I chek in the code they change to type 1 and 0 ... I think that it is because (I don't know why the pointers of the subnodes points to same direction).. but it mustn't change..
where list and order list I've defined like *list and I've saved space in memory using malloc...
I don't know what it's happening...
can anyone help me??
There are at least two problems with your code: one serious, one in terms of naming.
In the function
no1
andno2
are passed by value. They are temporary objects, for all practical purposes. So the linesare problematic. You're pointing the pointers to objects that will soon die. Once the function exists, you cannot count on anything that's in them. They are just garbage objects.
Consider passing the objects by address, not by value:
and
In
This is surely not a probability. You mean probably cardinality.