Kavish Dwivedi
Kavish Dwivedi

Reputation: 121

Double pointers as function arguments

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?

Upvotes: 0

Views: 1790

Answers (3)

Mike Dunlavey
Mike Dunlavey

Reputation: 40659

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;
    }

Upvotes: 0

simonc
simonc

Reputation: 42165

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.

Upvotes: 2

A B
A B

Reputation: 4148

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.

Upvotes: 0

Related Questions