Cで構造体とリンク リストを使用する方法を学習しようとしていますが、次のコードでセグメンテーション エラーが発生する理由がよくわかりません。
list.h、operations.c、および main.cという名前の 3 つのファイルがあります。ファイル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);
ファイル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');
}
}
ファイルmain.c :
#include "list.h"
int main(void) {
LINK head = string_to_list("wtf");
print_list(head);
return 0;
}