Why are changes made to a pointer inside a function not visible outside the function?

Viewed 168

I am implementing a linked list. There is a problem: when I change a pointer inside a function, the change is not visible outside of the function.

#include<bits/stdc++.h>
using namespace std;
//define

class List{
    public:
    int data;
    List *next;
    public:
        List(int n){
            this->data=n;
            this->next=NULL;
        }
};

void add(List *head,int data){
    List * nn = new List (data);
    head=nn;
}
// driver code
int main(){
    List *head=NULL;
    List * nn = new List (45);
    head=nn;
    cout<<head->data;
    return 0;
}

This code is printing 45.

class List{
    public:
    int data;
    List *next;
    public:
        List(int n){
            this->data=n;
            this->next=NULL;
        }
};

void add(List *head,int data){
    List * nn = new List (data);
    head=nn;
}
// driver code
int main(){
    List *head=NULL;
    add(head,45);
    cout<<head->data;
    return 0;
}

This program prints nothing. It simply crashes.

2 Answers

This function:

void add(List *head, int data)

takes the head pointer by copy, so changes to the pointer inside the function are not visible to the caller. This means the pointer head in main is not pointing to valid memory, and dereferencing it invokes undefined behavior (which could cause the crash).

Make the function take the pointer by reference instead:

void add(List * &head, int data)

and now changing head inside the function changes head in the main function.

There are 2 issues in add method:

1) You need to accept pointer to reference (or pointer to pointer)

2) You need to add logic to traversal until the last node in the list and add the new node at the end. Otherwise everytime you are resetting list head with new node and new node is pointing to null and becoming one node list.

Similar implementation you can refer here https://github.com/alokkusingh/DataStructure . The implementation is in C (not C++)

Related