I'm sure this is a very common problem. No matter how many times I've delt with pointers, they always end up confusing me. Especially in c.
I'm trying to pass a pointer to the root of a binary tree in a function, have the function change/add to the contents of the children, then return the original pointer. Here is the code:
Code:
struct node*
addword(struct node* p, char *w)
{
int cond;
struct node* i = p; //create iterator pointer
while (i != NULL) {
if ((cond = strcmp(w, i->word)) == 0) {
i->count++;
return p;
}
else if (cond < 0) {
i = i->left;
}
else {
i = i->right;
}
}
i = talloc(); // allocates new 'struct node'
i->word = strdup(w);
i->count = 1;
i->left = i->right = NULL;
return p;
}
I'm sure you can tell what I'm trying to do. I made a dummy pointer 'i' so I can iterate through my tree (ie i = i->right; ), then I can return the original pointer p. But no matter what I do to the pointer i, the pointer p does not change when it is returned. I know there is most likely a stupid mistake somewhere in here, but I've been playing with it for hours and reading countless pointer tutorials. I just can't seem to get it to work.
Can you guys help me out a bit?
Thanks,