Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Binary Tree and an Exception Throw ...

Status
Not open for further replies.

ankan

Programmer
Jun 22, 2001
70
US
If u don't have the pateince to go through the code below just skip to the 'Problem' written way below. But please help in anyway you can.

Lets get to the point directly...
A simple binary tree...
struct tnode {
char **word; /* this stores the different words */
int count; /* this keeps the count */
struct tnode *left;
struct tnode *right;
};

The simpler objective... to store in the above tree and print out each group of words from an input buffer that have the first few (how many? given by the variable 'till') characters identical, in alphabetical order.
The words are sent to the function addtree:

struct tnode *addtree(struct tnode *p, char *w, int till)
{
int cond;
if(p==NULL) { /* found new */
p = (struct tnode *) malloc(sizeof(struct tnode));
p->count = 1;
p->word[(p->count)-1] = strdup(w);
p->left = p->right = NULL;
} else if((cond = strncmp(w, p->word[0], till)) == 0) { /* found a match */
p->count++;
p->word[(p->count)-1] = strdup(w);
printf("Added to old... new: %s\n", w);
} else if(cond < 0)
p->left = addtree(p->left, w, till);
else
p->right = addtree(p->right, w, till);
return p;
}

The main fiunction ...
int main()
{
struct tnode* root;
int till = 6;
/* ... */
/* --------- snip ------ */
root = NULL;
while (getw(word, in) != EOF) /* getw() gets the next word from the input stream 'in' */
if(isalpha(word[0]))
root = addtree(root, word, till);
treeprint(root); /* a function traversing the binary tree for printing */
/* --------- snip ------ */
/* ... */
}

The Problem ... Its not running correctly. Sometimes it prints out only the last word. Sometimes the &quot;This program has performed an illegal operation...&quot; message crops up. And sometimes its not running at all!! There maybe a problem with the pointers. But where??
On stepping through with the Debugger it gave &quot;Stopped at exception throw&quot; error. And also the root->word (in main) gets changed with every call to the recursive function (although the address of root does not change, it should not anyway). But it seems (after much tracing through the code with the debugger) that the malloc function (bolded) in the recursive function gives the same address to p in each subsequent recursive call!!

Where did I go wrong?
Can you help?? Please.
Please do correct me if I am wrong. :)
 
The problem's solved, thanks to Zyrenthian (& me!!). Go to Thread206-112889 if you care to know the details.

Bye.
Ankan.

Please do correct me if I am wrong. s-)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top