0

I am having problem while initializing the node value to passed pointer in C language,

I have written something like follow,

#include<stdio.h>
#include<stdlib.h>
struct node{
    int data;
    struct node *next;
};

void add(struct node *head, int val){
    struct node *n1 = NULL;
    n1 = (struct node *)malloc(sizeof(struct node ));
    n1 -> data = val;
    n1 -> next = NULL;

    if(head == NULL){
        head = n1;
        printf("Head2 is initialized");
        return;
    }
}


int main(){
    struct node *ptr = NULL;
    struct node *temp;
    add(ptr, 11);
    printf("\nData = %d", ptr->data);
    return 0;
}

Could you please tell me what is the issue in this code,

When i execute

printf("\nData = %d", ptr->data);

System shows Windows has stopped working

Thanks

Alpesh Jikadra
  • 1,692
  • 3
  • 18
  • 38

1 Answers1

4

short answer: if you want to change the value the pointer points to, you have to pass the pointer to the pointer:

void add(struct node **head, int val) {
   ...
    if(*head == NULL){
       *head = n1
}

int main(){
   ...
    add(&ptr, 11)
   ...
}

long answer: when you call add(ptr, 11) in main you pass a memory address and a number. both memory address and a number are passed by value. as the result the changes to these variables are both local

in your add method - when you assign a value to head in head = n1 you change the value of your local variable to point to a new memory address. when your function returns the changes are gone, so main never sees the assignment and ptr remains NULL.

if you pass a pointer to ptr - &ptr, you will pass a location in memory where the value of ptr (which is memory address) resides in main, so when you call *head = n1* you write the address ofn1` the value in this location will change, and main will see it.

see also this question

Community
  • 1
  • 1
Effie
  • 758
  • 5
  • 15