Search code examples
cpointersstructure

Root pointer of linked list keeps varying when passed to a function in header file, How to keep it constant?


I've created a header file with some basic linked list functions, one of them is append(), which takes a struct node* pointer and value as argument. so when I call the function, for some reason the root value gets changed, so I had to keep passing the root pointer from the called and main. Is their a way to correct this?

**what I've tried : **

**main source code : **

#include"singly_linked_list0.h"

struct node* root = NULL;

int main(){
    int n = 5;
    while(n > 0){
        root = append(root, n);
        n--;
    }
    print_all(root);

    return 0;
}

** header function : **

/*appends the value passed at the end, and returns the ROOT*/
struct node* append(struct node* ROOT, int d){
    struct node *temp;
    temp = (struct node*)malloc(sizeof(struct node));
    temp->data = d;
    temp->link = NULL;
    if(ROOT == NULL) ROOT = temp;
    else{
        struct node *p;
        p = ROOT;
        while(p->link != NULL){
            p = p->link;
        }
        p->link = temp;
    }

    return ROOT;
}

Solution

  • You could pass a pointer to the root pointer to your append function:

    void append(struct node **ROOT, int d){
        struct node *temp = malloc(sizeof(*temp));
    
        // Check whether malloc was successful. Otherwise, exit with error
        if (temp == NULL)
            exit(-1);
    
        temp->data = d;
        temp->link = NULL;
    
        // If there is no root node yet, this can be set directly
        if (*ROOT == NULL)
            *ROOT = temp;
        // Otherwise, it is not touched
        else {
            struct node *p = *ROOT;
            while(p->link != NULL){
                p = p->link;
            }
            p->link = temp;
        }
    }
    

    It's then called via append(&root, n).

    Credit: As P__J__ mentioned there were some other issues in the code that are fixed here.