Pointer to structure

T

Tomek

Hello,

lets say i have some structure

struct Node {
int key ;
Node *left, *right ;
}

then in main() i declare pointer to structure like this

Node *root = NULL ;

then i want to send this pointer to function which will
add new Node, definition of this function looks like this:

void AddNode(Node *root) {
Node *anothernode = new Node ;
anothernode->left = anothernode->right = NULL ;

if( root == NULL )
root = anothernode ;
// ok rest code is not important here
}

the main problem is when i return from function AddNode
my pointer called "root" doesnt remember address of pointer
"anothernode", any idea why ?

Thanks in advance,
Regards
tommy
 
R

Rade

void AddNode(Node *root) {
Node *anothernode = new Node ;
anothernode->left = anothernode->right = NULL ;

if( root == NULL )
root = anothernode ;
// ok rest code is not important here
}

the main problem is when i return from function AddNode
my pointer called "root" doesnt remember address of pointer
"anothernode", any idea why ?

Because the argument 'root' of AddNode is not the same object as the global
variable 'root'. The former exists only within the AddNode function, but
hides the latter because they have the same names (imagine you have renamed
each occurence of 'root' within AddNode - the code would work the same
way!).

Fix it in one of two ways:

1) If you know that AddNode should specifically modify the global variable
root, then you don't need to pass it as an argument. Simply write:

void AddNode()
{
Node *anothernode = new Node ;
anothernode->left = anothernode->right = NULL ;

if( root == NULL )
root = anothernode ;
// ok rest code is not important here
}

2) If AddNode has to modify not only the global variable root, but also any
other Node * variable, then pass it as a reference to a Node pointer:

void AddNode(Node * &root)
{
Node *anothernode = new Node ;
anothernode->left = anothernode->right = NULL ;

if( root == NULL )
root = anothernode ;
// ok rest code is not important here
}

3) An old-fashioned, more-like-C solution, which is probably equivalent to
(2) with most compilers:

void AddNode(Node **root)
{
Node *anothernode = new Node ;
anothernode->left = anothernode->right = NULL ;

if( *root == NULL )
*root = anothernode ;
// ok rest code is not important here
}

Rade
 
R

Rade

Note also that, when you make it work, if root is not NULL, you have a
memory leak (anothernode allocated and never freed). Do you really need to
allocate it before you check if root is NULL?

Rade
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top