C 程序 : Create Linked List Using argv, argc,段错误

标签 c command-line linked-list argv argc

我有一个程序使用命令行提示符 argv 和 argc 接收字符串。我在运行代码时不断遇到段错误,经过大量研究后,我无法确定是什么原因造成的。也许我如何执行代码是问题所在?我正在使用 gcc -o code code.c 然后 ./code 一二三 其中一二三是添加到链表的字符串。任何帮助确定我的错误可能在哪里的帮助都会很棒。

这是我的代码:

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

typedef struct list_node_s{
    char the_char;
    struct list_node_s *next_node;
}list_node;

void insert_node(list_node *the_head, char the_char);
void print_list(list_node *the_head);

int main(int argc, char *argv[]){
    char next_char;
    list_node *the_head = NULL;
    insert_node(the_head, next_char);
    the_head->next_node = malloc(sizeof(list_node));
    if(the_head == NULL){
            return 1;
    }

    the_head->the_char = 1;
    the_head->next_node == NULL;
    int the_count, the_count2;
    for(the_count = 0; the_count < sizeof(argv); the_count++){
            for(the_count2 = 0; argv[the_count][the_count2] != '\0'; the_count2++){
                    next_char = argv[the_count][the_count2];
                    insert_node(the_head, next_char);
            }
    }

    print_list(the_head);
    return (0);
}

void insert_node(list_node *the_head, char the_char){
    list_node * current_node = the_head;
    while (current_node->next_node != NULL) {
        current_node = current_node->next_node;
    }

    current_node->next_node = malloc(sizeof(list_node));
    current_node->next_node->the_char = the_char;
    current_node->next_node->next_node = NULL;
}

void print_list(list_node *the_head){
    if(the_head == NULL){
            printf("\n");
    }else{
            printf("%c", the_head->the_char);
            print_list(the_head->next_node);
    }

}

最佳答案

改变这个:

list_node *the_head = NULL;
insert_node(the_head, next_char);
the_head->next_node = malloc(sizeof(list_node));

到:

list_node the_head = { '\0', NULL };

the_head初始化为一个空节点。

关于C 程序 : Create Linked List Using argv, argc,段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23124410/

相关文章:

list - 如何在 Racket 中创建一个可以按照添加元素的顺序进行迭代的列表?

c - 为什么递归函数调用需要返回一个值给调用函数?

c - 使用毫();按下按钮后延迟

git - 您如何以不同的用户身份提交代码?

curl - 使用 wget 部分下载

php - 有没有一种简单的方法可以在命令行中本地设置断点并调试 PHP 脚本?

明确绑定(bind)()套接字函数

C,帮助我理解这个 ASCII 问题

c++ - 乱码编译器 (MinGW) 输出

c - C 中的链表示例