I am trying to implement a binary search tree by reading lines from a file.
while(fgets(p, 1024, fp))
{
struct node child;
child.str = (char *)malloc(plen);
strcpy(child.str,p);
insert(&tree,&child);
}
Now the problem is that I can not seem to find a way to make a complete new copy of child, instead it just changes its values every time the while loop restarts.
That’s because the pointer-to-child (
&child) isn’t changing. You can convince yourself of this by printing it out:Solution: You also need to allocate the node as well:
You can then assign
child.stras you were, now using pointer-syntax:…and because the child is a pointer, you don’t need the ampersand here: