I am trying to learn how to use structures and linked lists in C but I really don't understand why the following code gives me Segmentation fault:
I have 3 files named list.h, operations.c and main.c. In the file list.h:
#include <stdio.h>
#include <stdlib.h>
typedef char DATA;
struct linked_list {
DATA d;
struct linked_list *next;
};
typedef struct linked_list ELEMENT;
typedef ELEMENT *LINK;
LINK string_to_list(char s[]);
void print_list(LINK);
The file operations.c:
#include "list.h"
LINK string_to_list(char s[]){
LINK head = NULL;
if (s[0]) {
ELEMENT c = {s[0], NULL};
c.next = string_to_list(s+1);
head = &c;
}
return head;
}
void print_list(LINK head) {
if(head != NULL){
putchar(head -> d);
print_list(head -> next);
} else {
putchar('\n');
}
}
The file main.c:
#include "list.h"
int main(void) {
LINK head = string_to_list("wtf");
print_list(head);
return 0;
}