0

I have been encountering a lot of linked list functions and C functions that intend to pass double pointer in place of single pointer to a function.For example this below function for sorted insert in a linked list :

    void sortedinsert(struct node **headref,struct node *newnode)
    {
           while(*headref!=NULL&&(*headref)->data<newnode->data)
                   headref=&((*headref)->next);
           newnode->next=headref;
           *headref=newnode;
    }

Please explain me about the use of double pointers as function arguments in place of single pointers and how does it eases of writing functions as above for linked lists?

3
  • I am not sure what you are asking. Can you phrase this in the form of a question? Commented Jan 15, 2013 at 16:40
  • 1
    c-faq.com/ptrs/passptrinit.html Commented Jan 15, 2013 at 16:40
  • 1
    In C arguments are passed by value. When you pass a pointer, only a copy of the pointer is passed. So if you want to change the original pointer in the caller, a double pointer is passed. Commented Jan 15, 2013 at 16:42

3 Answers 3

2

This "double pointer" is a pointer to a pointer. It allows the caller's copy of the pointer to be updated by the sortedinsert function when it updates the list's head item.

The line *headref=newnode; updates the caller's pointer to point to newnode. (As an aside, I think the code is questionable. It looks like headref is always set to newnode, regardless of the list position newnode was inserted at.)

Note that you could avoid using a pointer to a pointer in this case by changing the function to return a pointer to the list's head instead.

Sign up to request clarification or add additional context in comments.

Comments

0

Notice if you were in C++, you could pass headref by reference, so the same code would be simpler. It does exactly the same thing, but it's simpler:

    void sortedinsert(struct node* &headref,struct node *newnode)
    {
           while(headref!=NULL && headref->data < newnode->data)
                   headref = headref->next;
           newnode->next = headref;
           headref = newnode;
    }

Comments

0

The sortedinsert function accepts a pointer to a pointer to the head of the list and a pointer to the new node.

The head of the list is just a pointer, but is a "pointer to a pointer" in this function because the function is changing the position of the head of the list.

The new node is added at the sorted position in the list, and the head appears to always be modified to point to the newest node.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.