-1

I dont want create general *head node and I want to pass by reference and chance my data but although create new node for next node I cant reach my new node on main. İf I look n1.next in main I see it is null.Why ?What is wrong ?

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

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

void add(struct node** head,int data){
    struct node * tmp = *head;

    while(tmp != NULL){
        tmp = tmp->next;
    }
    tmp = (struct node*) malloc(sizeof(struct node));
    tmp->data= data;
    tmp->next=NULL;
}

int main()
{
    struct node n1;

    n1.data=5;
    n1.next=NULL;

    add(&(n1.next),15);
    printf("%d",n1.next->data);

    return 0;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
reddawn
  • 11
  • 6

1 Answers1

0

Instead of using a head pointer, are you trying to pass in the last next pointer in the list, and then update that to point to your new node? If so, add() should be

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

    *head = p;
}
Stephen Docy
  • 4,738
  • 7
  • 18
  • 31