-2

In the main function, I've created a head and push front using a function and it works as expected.

However, after using this function to add an information at the end the created node, it doesn't.

The push back data doesn't get attach to the linked list.

Below is my code;

// function pushback using tail   
void push_back_t(Node *tail, int data) {
    Node *Sn = (Node*)malloc(sizeof(Node));  //creation of the new node called Sn
    if (Sn == NULL) {
        printf("Erreur");
        exit(3);
    }
    Sn->data = data;  //to add the data to the new node
    Sn->Next = NULL;
    tail->Next = Sn;  //make the last Node that tail already point points on the new node
    tail = Sn;  //make tail to the last and new node 
}

What am I doing wrong and how can I fix it?

nyedidikeke
  • 6,899
  • 7
  • 44
  • 59
  • 1
    Your problem is that `tail = Sn` will only update (the local copy of) `tail` in this function, but not any references you have outside. There are several ways to get around this. If you keep a tail, you probably have an enclosing struct that also contains the head, haven't you? – M Oehm Apr 06 '19 at 10:28
  • @prezzmainfo: you can accept one of the answers by clicking on the grey checkmark below its score. – chqrlie Apr 13 '19 at 11:39

2 Answers2

0

You must update tail in the calling code. Alternately, you could pass a pointer to the tail pointer:

// function pushback using tail   
void push_back_t(Node **tail, int data) {
    Node *Sn = (Node *)malloc(sizeof(Node));  //creation of the new node called Sn
    if (Sn == NULL) {
        printf("Erreur");
        exit(3);
    }
    Sn->data = data;  //to add the data to the new node
    Sn->Next = NULL;
    if (*tail) {
       (*tail)->Next = Sn;  //make the last Node that tail already point points on the new node
    }
    *tail = Sn;  //make tail point to the new last node
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
0

It happens because tail is passed by value, so you are changing a copy of it inside the function, not the original one.

You must change the function to make it take a pointer to pointer to Node, i. e. Node **tail, and dereference it inside the function.

void push_back_t(Node **tail, int data) {
    ... 
    if(*tail) {
        (*tail)->Next = Sn;
    } 
    *tail = Sn;
} 
machine_1
  • 4,266
  • 2
  • 21
  • 42