dimanche 31 juillet 2016

Why am I getting a segmentation fault in my LinkedList insertion method in C

The segmentation fault occurs at the line "else if(head -> next == NULL){". I feel like I'm missing something fundamental about pointers.

Here is the code.

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

typedef struct Node{
    int value;
    struct Node* next;
}Node;

void insert(Node* head, int value){
    if(head == NULL){
        head = (Node*)malloc(sizeof(struct Node));
        head -> value = value;
        head -> next = NULL;
    }else if(head -> next == NULL){
        printf("goodn");
        head -> next = (Node*)malloc(sizeof(struct Node));
        head -> next -> value = value;
        head -> next -> next = NULL;
    }else{
        insert(head -> next, value);
    }
}

int main(){
    struct Node* head;
    head = NULL;
    insert(head, 3);
    insert(head, 4);
    printf("%dn", head -> value);
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire