0

Even though I am assigning the newly created node, the head always points to NULL only. when I debugged, at head = temp it's getting the correct value. But after I get exit from the function, I got NULL in head pointer. I supposed malloc will allocate global memory. Can anyone pls help what is the mistake that I am doing here? I am getting "list is empty" after I enter any input

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *next;
};

void display(struct Node *head);
void addNode(struct Node *head,int data);

int main(void) {
    struct Node *head = NULL;
    int data;
    printf("Enter the data");
    scanf("%d", &data);
    addNode(head,data);
    display(head);
}

void addNode(struct Node *head,int data) {
    struct Node *temp = (struct Node*) malloc(sizeof(struct Node));
    temp->data = data;
    temp->next = NULL;
    if (head == NULL) {
        head = temp;
        return;
    } else {
        struct Node *ptr = head;
        while (ptr->next != NULL)
            ptr = ptr->next;
        ptr->next = temp;
    }
}
void display(struct Node *head) {
    struct Node* ptr;
    if (head == NULL)
        printf("list is empty");
    else {
        while (ptr != NULL) {
            printf("%d\n", ptr->data);
            ptr = ptr->next;
        }
    }
}
Madhava
  • 11
  • 2
  • 2
    You pass `head` by value to `addNode`, so in `addNode` you modify a local copy that doesn't get passed back to the caller. You have to change the parameter to `struct Node **head` and use `*head` instead of `head` in `addNode` and pass the address of the pointer in `main`. – Bodo Apr 08 '20 at 14:19
  • see e.g. https://stackoverflow.com/a/24052548/10622916 – Bodo Apr 08 '20 at 14:24
  • thanks@Bodo. So whenever we pass a pointer like int *ptr; func(ptr), we are actually passing the pointer as a value just like we with variables?. – Madhava Apr 08 '20 at 14:56
  • @Bodo no, you don't have to do that. Returning the head as a function result would also work fine and avoid the double-star. – Martin James Apr 08 '20 at 14:57
  • Thanks @Bodo@Marin James. I have tried both the ways returned the head pointer after addNode() and also passed the address of the head pointer and did *head==NULL. Both are working fine. – Madhava Apr 08 '20 at 16:04

0 Answers0