我编写了一个程序,它从命令行获取参数,并使用结构递归地构建链接列表。它还递归打印列表。但是,当我尝试运行此程序时,我遇到了分段错误。我的编译器是gcc。如果有人能告诉我故障发生的地方,那将是非常有帮助的。谢谢!
#include <stdio.h>
#include <stdlib.h>
typedef struct list_node{
char in_data;
struct list_node *next_item;
} list_node;
list_node *add_node(char input_x, list_node node_name);
void print_list(list_node *head_of_list);
int main(int argc, char *argv[]){
int looper_1;
int looper_2;
char next_char;
list_node *head_ptr;
list_node head_node;
for(looper_1 = 1; looper_1 < argc; looper_1++){
for(looper_2 = 0; argv[looper_1][looper_2] != '\0'; looper_2++){
if(looper_1 == 1 && looper_2 == 0){
next_char = argv[looper_1][looper_2];
head_ptr = add_node(next_char, head_node);
}
else{
next_char = argv[looper_1][looper_2];
add_node(next_char, head_node);
}
}
}
print_list(head_ptr);
return 0;
}
list_node *add_node(char input_x, list_node node_name){
list_node place_holder;
list_node *place_ptr;
if(node_name.in_data == -1){
node_name.in_data = input_x;
node_name.next_item = place_ptr;
}
else{
node_name.next_item = add_node(input_x, place_holder);
}
list_node *new_ptr = &node_name;
return new_ptr;
}
void print_list(list_node *head_of_list){
if(head_of_list->in_data == -1){
printf("NULL");
}
else{
printf(" %c", head_of_list->in_data);
print_list(head_of_list->next_item);
}
return;
}