grace lee
grace lee

Reputation: 11

giving pointer parameter in recursive call

I have a easy pointer question for expert. This function creates a copy of linked list. The last line, it is a recursive call of copyLinkedList. I can't figure out giving parameter of pointer to pointer where I put ??

How can I easily understand this complicated pointer things? (still difficult for me )

* Thank you *

void copyLinkedList(struct Node *node, struct Node **ppNode)
{
    if (node){
        *ppNode = new Node;
        (*ppNode)->data = node->data;
        (*ppNode)->next = NULL;
        copyLinkedList(node->next,  ?? );
    }
}

Upvotes: 1

Views: 33

Answers (2)

John Humphreys
John Humphreys

Reputation: 39254

When you pass a pointer (single) into a function, it is passed-by-value. So, you basically have a copy of the pointer you passed into the function, and if you modify it, it does not change the original pointer which was passed in - the caller will never see it.

If you pass a pointer-to-a-pointer, you can de-reference it which allows you to change the original pointer which was passed in by the caller.

In your case, *ppNode = new Node; assigns a new node to the pointer the user passed in (i.e. the pointer that the pointer-to-a-pointer points to)... I know, that sounds horrible - but you can draw it out and it makes sense.

You set the data and the next value of that new pointer to the value from the original list. Now you want to move on to the next element. So, you're passing to the recursive call the next element of the original list, AND the next element of the new list you're creating. So, you want to pass in a pointer to the "next" pointer of the element you just created.

  • The node you just created is *ppNode (de-referenced the pointer).
  • The next node in the list after *ppNode is the ->next member.
  • The pointer to the next member is what you get when you take the address of the next member.

So, &(*ppNode)->next - @StenSoft already provided the full call though.

Upvotes: 0

StenSoft
StenSoft

Reputation: 9609

Well, you want to pass pointer to (*ppNode)->next:

copyLinkedList(node->next, &(*ppNode)->next);

Upvotes: 1

Related Questions