Thread: Function which insert one Node in a List

  1. #1
    Registered User
    Join Date
    Jun 2019
    Posts
    33

    Function which insert one Node in a List

    Hi everybody,

    I'm writing this post because I can't understand a function, which is thought to insert a node at the beginning of a linked list.

    Here we have the function:

    void pre_insert(struct list ** doubleptr, float value);

    Code:
    void pre_insert(struct list ** doubleptr, float value) { 
    /*INPUT of the function:
    -pointer which points to a pointer which points to a record;
    -float.*/
    
    struct list * temporary; /*I create a pointer to a record*/
    
    
        temporary = *doubleptr; /*The pointer I created point to the pointer
    pointed by the doublepointer of the input*/
    
    
        *doubleptr = (struct list *)malloc(sizeof(struct list)); /*I create a new record, 
    I give his adress to the double pointer of the input*/
    
    
        (*doubleptr)->value = value; /*I can't understand what happen here*/
        (*doubleptr)->next_ptr = temporary;/*I can't understand what happen here*/
        }

    Can anyone tell me:
    - if the sentences written as comments are correct;
    - what happen in the last two lines.
    Thank a lot!!!
    Last edited by letthem; 06-24-2019 at 03:04 PM. Reason: Font size abuse

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Well you are going about it backwards.

    Naming all your variables 'tmp' and 'ptr' doesn't add any clarity either.

    Code:
    void pre_insert(struct list **head, float value) { 
        struct list *newnode = malloc(sizeof(*newnode));
        newnode->value = value;
        newnode->next = *head;
    
        *head = newnode;
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. linked list insert node between two nodes.
    By dasmonk in forum C Programming
    Replies: 8
    Last Post: 10-25-2013, 03:26 PM
  2. Insert a node into the end of a linked list
    By aw1742 in forum C Programming
    Replies: 4
    Last Post: 10-12-2011, 03:50 PM
  3. Insert node in a linked list.
    By antonis in forum C Programming
    Replies: 2
    Last Post: 10-22-2005, 02:30 PM
  4. Replies: 4
    Last Post: 09-10-2005, 01:07 PM
  5. Replies: 5
    Last Post: 10-04-2001, 03:42 PM

Tags for this Thread