|
-
November 14th, 2008, 05:08 AM
#1
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
Last edited by Moghammed; November 16th, 2008 at 04:50 AM.
-
November 14th, 2008, 06:54 AM
#2
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.
More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity. --W.A.Wulf
Premature optimization is the root of all evil --Donald E. Knuth
Please read Information on posting before posting, especially the info on using [code] tags.
-
November 14th, 2008, 01:40 PM
#3
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
-
November 14th, 2008, 09:21 PM
#4
Re: Pointer Panic
Thanks for your help.
-
November 16th, 2008, 05:12 AM
#5
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
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|