I've decided to go through all of D&R's exercises and in doing so I have encountered a peculiar event. Based on the book's own addtree
function I modified it for my own structure:
struct gnode {
char **words;
int count;
struct gnode *left;
struct gnode *right;
};
And it now is:
struct gnode *addtree(struct gnode *p, char *w) {
int cond;
if (p == NULL) {
printf("init null node\n");
p = (struct gnode *)malloc(sizeof(struct gnode));
//MISTAKE I WAS MAKING:
// struct gnode *p =(struct gnode *)malloc(sizeof(struct gnode));
//p would be NULL every time.
p->count = 1;
p->words = malloc(8);
p->words[0] = strdup2(w);
p->left = p->right = NULL;
} else
if ((cond = compare(w, p->words[0])) == 0) {
printf("comp hit\n");
p->count++;
p->words = realloc(p->words, p->count * 8);
p->words[p->count] = strdup2(w);
} else
if (cond < 0)
p->left = addtree(p->left, w);
else
p->right = addtree(p->right, w);
return p;
}
I would like to know why if a local pointer with the same name as the argument is returned, it is NULL
every time.