My question is about pointers to pointers. A book I’m using to teach myself C++ uses a function whose first argument is a pointer to a pointer and receives the address of the root pointer into that binary tree class insertion function. It says that it uses the pointer to a pointer in order to modify the pointer's value. In general, why would one ever have to use a pointer to a pointer, instead of just passing the pointer itself? It just seems like a needless extra step to me.
The code is posted below:
Code:
template< class NODETYPE>
void Tree<NODETYPE>::insertNode(const NODETYPE &value)
{
insertNodeHelper( &rootPtr, value);
}
template< class NODETYPE>
void Tree<NODETYPE>::findNode(const NODETYPE &value)
{
findNodeHelper( &rootPtr, value);
}
template< class NODETYPE>
void Tree<NODETYPE>::insertNodeHelper( TreeNode< NODETYPE> **ptr, const NODETYPE &value)
{
if(*ptr == 0)
*ptr = new TreeNode< NODETYPE> (value);
else
if (value < (*ptr)->data)
insertNodeHelper(&((*ptr)->leftPtr), value);
else
if (value >(*ptr)->data)
insertNodeHelper(&((*ptr)->rightPtr), value);
else cout << value << " dup" << endl;
}