-
pointer to a pointer
I need help in understanding some example code. If you want to delete the last node of the list L, why does the parameter have to be a pointer to a variable containing a node pointer? In other words why is it **L? Is there any list example that would not have its last node deleted if the parameter had been only a node pointer as in the function prototype void DeleteLastNode(NodeType *L)
Code:
void DeleteLastNode(NodeType **L)
{
NodeType *PreviousNode, *CurrentNode;
if (*L!=NULL)
{
if ((*L)->Link == NULL)
{
free(*L);
*L=NULL;
}
else
{
PreviousNode=*L;
CurrentNode=(*L)->Link;
while (CurrentNode->Link!=NULL)
{
PreviousNode=CurrentNode;
CurrentNode=CurrentNode->Link;
}
PreviousNode->Link=NULL;
free(CurrentNode);
}
}
}
-
> In other words why is it **L?
When there is only one node in the list, the last node is also the first node.
Then you really need to update the pointer which points to the list.
-
If you had only passed a single pointer to the routine then the routine would have the address of the memory pointer only. By passing a double pointer you are getting the address of what the pointer points to and that is the memory that you are trying to alter.
The only analogy that I could think of to help explain this is to think of it in terms of a post office and your home:
A post office knows where your house is based upon your address. However, the post office is itself a location which has an address but obviously not your house. The post office is the pointer. Your address (where your actual house resides) is the data. I don't know if this elaboration helps at all or has confused you more.