Search code examples
cstructlinked-listsingly-linked-listfunction-definition

Function to insert a node in a linked list in C


I'm trying to learn data structures in C and I'm stuck at the first function I made. If I run this nothing happens.
I get no errors but the program doesn't print anything.


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

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

void insert(int data, node *head){
    node *new_node = malloc(sizeof(node));
    new_node->data = data;
    head = new_node;
}

int main(){
    node *head = NULL;
    insert(8, head);
    printf("head.data: %d\n", head->data);
}

But if I put the code from the function insert in the main function it works.

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

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

int main(){

    node *head = NULL;
    node *new_node = malloc(sizeof(node));
    new_node->data = 5;
    head = new_node;
    printf("head.data: %d\n", head->data);
}

Do I not know how to use functions in C or what is the problem with my first code?


Solution

  • In this call

    insert(8, head);
    

    the pointer head is passed to the function by value.

    It means that the function deals with a copy of the value of the pointer.

    Changing the copy within the function does not reflect on the original value of the pointer.

    Either you need to pass the pointer by reference through a pointer to it or to return the new value of the pointer from the function and to assign it to the original pointer.

    Also you forgot to set the data member next of the created node to NULL or more precisely to head.

    Here you are.

    int insert( node **head, int data )
    {
        node *new_node = malloc( sizeof( node ) );
        int success = new_node != NULL;
    
        if ( success )
        {
            new_node->data = data;
            new_node->next = *head;
            *head = new_node;
        }
    
        return success;
    }
    

    and the function is called like

    insert( &head, 8 );
    

    or

    if ( !insert( &head, 8 ) )
    {
        puts( "Error: not enough memory." );
    }
    

    Another approach is to return the new value of the pointer head from the function.

    For example

    node * insert( node *head, int data )
    {
        node *new_node = malloc( sizeof( node ) );
        
        if ( new_node != NULL )
        {
            new_node->data = data;
            new_node->next = head;
        }
    
        return new_node;
    } 
    

    In this case you need to use the function with caution.

    For example

    node *tmp = insert( head, 8 );
    if ( tmp != NULL ) 
    {
        head = tmp;
    }
    else
    {
        puts( "Error: not enough memory." );
    }