【发布时间】:2013-05-16 17:38:26
【问题描述】:
我正在尝试学习如何在 C 中使用结构和链表,但我真的不明白为什么下面的代码会给我分段错误:
我有 3 个文件,分别名为 list.h、operations.c 和 main.c。在文件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;
}
【问题讨论】:
-
从不返回对本地存储的引用。
-
就目前而言,如果没有一些动态内存分配或一些花哨的池工作,您将无法在列表中拥有超过 1 个元素。
-
@CaptainSkyhawk:实际上他有,但时间不长。
标签: c segmentation-fault undefined-behavior