0

I think I'm missing something important about pointers and memory. This is the minimum code needed:

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

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


struct node* init(int value) {
    struct node* head = (struct node*)malloc(sizeof(struct node));
    if (!head) return NULL;
    head->value = value;
    head->next = NULL;
    return head;
}

void insert_back(struct node* head, int value) {
    if (!head) return;
    struct node* temp = head;
    struct node* new = (struct node*)malloc(sizeof(struct node));
    while (temp->next != NULL) {
        temp = temp->next;
    }
    temp->next = new;
    new->value = value;
    new->next = NULL;
    return;
}

struct node* insert_front(struct node* head, int value) {
    struct node* temp;
    struct node* new = (struct node*)malloc(sizeof(struct node));
    new->value = value;
    new->next = head;
    temp = head;
    head = new;
    head->next = temp;
    return new;
}

void insert_front_2(struct node* head, int value) {
    struct node* temp;
    struct node* new = (struct node*)malloc(sizeof(struct node));

    new->value = value;
    new->next = head;

    temp = head;

    head = new;
    head->next = temp;
}

void print_list(struct node* head) {
    if (!head) return;

    struct node* temp = head;
    int i = 0;
    while (temp != NULL) {
        printf("At position %d value %d \n", i, temp->value);
        i++;
        temp = temp->next;
    }
}

int main() {
   struct node* head = init(5);
    insert_back(head, 7);
    insert_back(head, 9);
    insert_back(head, 12);
    insert_back(head, 13);
    insert_back(head, 14);
    insert_back(head, 15);

    head = insert_front(head, 100);
    insert_front_2(head, 200);
    print_list(head);
    free(head);
    return 1;
}

The problem concerns the function void insert_front_2(...). I do not understand why struct ndoe * instert_front works perfectly, but insert_front_2 does not hold the new head once I am in the main - that is, when I print the list, the new head is not printed. Any ideas? How should I modify void insert_front_2(...) to make it work?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 2
    In C all function params are passed by value. It means that `head` is a local variable in the function. Setting it does not change the caller's value. See duplicate post for more details and ways to fix it (returning the head is one option as you have done in `insert_front`; – kaylum Nov 01 '21 at 10:39
  • 1
    https://stackoverflow.com/a/605856/140750 – William Pursell Nov 01 '21 at 10:45
  • Thanks for the explanation. Also the other post is indeed useful for more details :) – bugs_and_stars Nov 01 '21 at 10:46
  • 1
    Draw what insert_front does on paper and see if you can cut out the extra statements. It will teach you a lot about pointers – stark Nov 01 '21 at 11:12
  • I will thanks for the tip – bugs_and_stars Nov 03 '21 at 07:37

0 Answers0