c - 如何修复此代码中的段错误

标签 c

这是链表程序,没有错误,但输出未正确显示 没有错误,但我认为逻辑不行,不使用函数就可以实现这个,只需要逻辑。

struct node * c;
struct node * head;

int n, i = 0;
scan("%d", & n);
if (n < 10) {

    for (i = 0; i < n; i++) {

        struct node * p;
        p = (struct node * ) malloc(size of (struct node));

        scan("%d", & p - > data);
        p - > next = NULL;

        c = NULL;

        head = NULL;
        if (head == NULL) {
            head = p;
        } else {

            c = head;
            while (c - > next != NULL) {

                c = c - > next;
            }
            c - > next = p;
            print("%d", c - > next);

            struct node * d = head;
            while (d != NULL) {
                print("%d", d - > data);
                d = d - > next;
            }

        }
}

这是链表程序,我添加了代码部分而不是整个 block

输入 10 20 30 时的预期结果 输出 10->20->30

最佳答案

我看到的主要问题。

    head = NULL;

您每次在 for 循环内都将 head 初始化为 NULL。 您应该在声明时进行初始化。

struct node * head = NULL;

还有

将打印代码移到 for 循环之外。

    struct node * d = head;
    while (d != NULL) {
        print("%d", d - > data);
        d = d - > next;
    }

关于c - 如何修复此代码中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55843433/

相关文章:

C - 通过 funcptr 调用函数,为什么不起作用?

c++ - 随机生成可被N整除的数字的最佳算法

c - 如何用 C 语言读取文本文件?

c - 如何使用 libgit2 获取单个文件的差异?

c - 正确取消引用字符串数组

c - 如果其他没有运行

c - asm 关键字作为 C 中的标识符名称?

c - 严格别名的性能优势

c - putc和putchar的性能?

c - 多次执行fork会带来什么风险?