Note that there are some explanatory texts on larger screens.

plurals
  1. POBinary tree implementation in C question as found in K&R
    text
    copied!<p>So I've been reading through the K&amp;R C book and have a question.. in the 6th Chapter on structs on page 140-141, there is code that looks like this (I took out some of the more irrelevant parts)</p> <pre><code>/* the program loops through a tree looking for some word if it finds the word itll incremenet the count by 1 if it doesnt itll add a new node */ struct node { char *word; int count; struct node *left; struct node *right; } main() { struct node *root; char word[1000]; root = NULL; while(getword(word, MAXWORD) != EOF) /* getword just grabs 1 word at a time from a file of words */ if(isalpha(word[0])) /* isalpha checks to see if it is a valid word */ root = addNode(root, word); treeprint(root); /* prints the tree */ return 0; } struct node *addNode(struct node *p, char *w) { int cond; if(p == NULL) { p = malloc(sizeof(struct node)); /* allocates memory for the new node */ p -&gt; word = strdup(w); p -&gt; count = 1; p -&gt; left = p -&gt; right = NULL; } else if ((cond = strcmp(w, p -&gt; word)) == 0) p -&gt; count++; else if(cond &lt; 0) p -&gt; left = addNode(p -&gt; left, w); else p -&gt; right = addNode(p -&gt; right, w); return p; } </code></pre> <p>And my confusion is in the main() function at root = addNode(root, word)</p> <p>If addNode returns a pointer to the newly added node (or to the node that word is at if its already int he tree), wouldn't that "lose" all the data above the tree? Shouldn't root stay as the root of the tree?</p> <p>Thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload