this is the complete code. node is a struct which contains a value, an ascii character, and an amount, the number of times this character appears. huffman_tree is a class which will receive incoming letters, sort 'em, and later on do all the compression work.Code:#include <iostream> #include <string> struct node { node* one; node* zero; char value; int amount; node (char x) { one=NULL; zero=NULL; value=x; amount=1; } void add() { amount++; } }; class huffman_tree { public: node *node_list[100]; int list_size; int search(char x) { for (int i=0;i<list_size;i++) { if (node_list[i]->value==x) { return i;} } } void add(char x) { int temp; if (temp=search(x)) { node_list[temp]->add(); return; } node_list[list_size]=new node(x); list_size++; node_list[list_size]=NULL; } huffman_tree() { list_size=0; node_list[0]=NULL; } void sort() { bubblesort(); } void bubblesort() { node* temp; int n=list_size; for (int i=0;i<n-1;++i) for (int j=1;j<n-i;++j) if (node_list[j-1]->value > node_list[j]->value) { temp=node_list[j]; node_list[j]=node_list[j-1]; node_list[j-1]=temp; } } }; int main() { huffman_tree tree; string temp="hello"; char letter; while (temp.length()) { letter=temp.at(0); temp.erase(0,1); tree.add(letter); } tree.sort(); for (int i=0;i<tree.list_size;i++) }
this code works when i comment out the "if (search(x))..." block. right now it comes up with a segmentation error on the second letter.
here's what i think's happening: (note: i put some cout statements to aid in debugging, then took them out when i posted the code)
a string is created. i pull the letters off the beginning of the string until there are none left, and store each letter in char letter. each letter is sent to tree->add().
tree->search() is supposed to return a non-zero if this letter was already added. in that event amount is supposed to increase by one on the letter to represent 2 of that letter. search isn't doing it's job. search() tests each node value and compares it to the given char. if yes, then it returns the position of the note. else it returns 0...
i think i found the problem. so just answer this: at the end of a function is return 0; implied, or does it just return some random number?