Recursive function to traverse linked list in reverse order
June 13, 2012
Function Templates in C++
June 14, 2012

Changing pointer passed to a function as argument

Solution to the problem:
If we want to change the actual pointer argument in the called function, then there are proper ways to do that.

In C++, there is a concept of reference variables, A reference variable is actually an alias of the original variable. We can modify the insert function to receive a reference to pointer variable. In which case head is not allocated a separate memory, but it will only be another name for the memory of list. So if we changehead, list gets changed.

    void insert(Node * & head, int value)
    {
        ... ...

In C language, there is no concept of reference, (In fact, pass-by-address is mistakenly used by some authors as pass-by-reference). So if we want the called function to be able to change a pointer we will have to pass a pointer to that pointer.

    void insert(Node ** head, int value)
    {
        ... ...

this will require us to use one more level of dereferencing in the above function in case of C language, but that’s how it can be implemented.

If we don’t want a function to change the pointer itself then we can declare the pointer variable (the formal argument in the called function) as a constant pointer, like below:

    void insert(Node *const head, int value);

Note that the above declaration (Node * const head) is different from

    const Node* head

The above indicates that the value pointed to be head is constant, and does not say that head itself is constant.

Leave a Reply

Your email address will not be published. Required fields are marked *