-
Pointer Panic
Hi all,
I'm writing a program that implements a binary search tree datastructure using pointers.
However, i have encountered a problem i can't seem to figure out...
Code:
void bst::addnode(int val)
{
findaspot(val);
node* newnode;
if(theplacetobe == root)
{
cout << "root is tha place to be" << endl;
newnode = root;
}
else
{
if(val >= theplacetobe->value)
{
newnode = theplacetobe->right;
}
else
{
newnode = theplacetobe->left;
}
}
newnode = new node;
newnode->value = val;
cout << endl <<"newnode value:" << newnode->value << endl;
cout << "root value: " << root->value << endl;
}
void findspot(int) sets pointer theplacetobe to the leaf of the tree where i want to add the new node. (for those who don't know: a binary search tree is a tree in wich new nodes have at most 2 children, the right one bigger than the node itself, the left one smaller.)
now here's the problem:
when the first node is added (and newnode therefore == root), newnode->value is equal to val
root->value, however is nonsense (somewhere around 9.000.000).
Why does this happen, when i have set newnode to be equal to root?
Many thanks in advance!!
-Mohammed
-
Re: Pointer Panic
Please edit your post and add code tags around your code. Read through the FAQ (via the Before you Post link) for details.
-
Re: Pointer Panic
Hard to read without code tags, but it appears that you are setting newnode to a new node:
Code:
newnode = new node;
This is most definitely not the same node as root.
Viggy
-
Re: Pointer Panic
-
Re: Pointer Panic
thx for your replies!!
sorry i didn't put the code in codetags, posted it too quickly and then couldn't find it back :S
I've solved it though..
for anyone interested:
obviously sets the pointers to the same memoryaddress
however, this:
Code:
newnode = new node;
sets newnode to a new address, which is kindof logical, as you can't be sure there is enough unreserved memory for the new object at the memory address newnode was pointing to.
a simple
after the creation of the new node solved the problem.
Greetz. Mo