【问题标题】:How to debug a linked list program? [closed]如何调试链表程序? [关闭]
【发布时间】:2016-06-16 12:27:56
【问题描述】:

我很难理解我的代码有什么问题,

正如你所看到的,它是一个链表,它应该连接“Boxes”,每个 Box 都有一个 int 值和一个指向下一个 Box 的指针,但是我无法让它运行而且我没有'不知道为什么。

谁能告诉我为什么它没有运行?

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

struct node {
    int n;
    struct node *next;  
} node;

typedef struct node Box;

main()
{    
    Box *q, *r, *s;
    Box t;

    q = (Box *)malloc(sizeof(Box));
    r = (Box *)malloc(sizeof(Box));
    s = (Box *)malloc(sizeof(Box));

    q->n = 2;
    q->next->n = 3;
    r->n = 4;
    q->next->next = r;
    r->next = NULL;
    s->n = 5;
    s->next = NULL;
    t.n = 6;

    printf("================");
    printf("Q == %d\n", q->n);
    printf("R == %d\n", r->n);
    printf("S == %d\n", s->n);
    printf("{%d}{%d}{%d}{%d}{%d}", q->n, q->next->n, r->n, s->n, t.n);      
}

【问题讨论】:

  • 欢迎来到 Stack Overflow!听起来您可能需要学习如何使用调试器来逐步执行代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。进一步阅读:How to debug small programs.
  • 在将q-&gt;next 指向任何东西之前,您先写q-&gt;next-&gt;n
  • 您需要提供相关的标题,以及“它不起作用”的意思

标签: c list pointers linked-list


【解决方案1】:

你为q分配内存

Box *q = malloc(sizeof(Box));

那么您使用q-&gt;next 而不分配它:

q->n = 2;
q->next->n = 3;

【讨论】:

    【解决方案2】:

    您的初始化序列非常混乱,这使得它通过写入未初始化的指针来调用未定义的行为。

    应该是:

    q->n = 2;
    q->next = r;
    r->n = 4;
    r->next = s;
    s->n = 5;
    s->next = t;
    t->n = 6;
    t->next = NULL;
    

    另外,please don't cast the return value of malloc() in C

    【讨论】:

      【解决方案3】:

      您正在写入未分配的内存:

      q->n = 2;
      q->next->n = 3; //q->next points "into the wild" here
      

      您可能打算这样:

      q = malloc(sizeof(Box));
      q->next = malloc(sizeof(Box));
      q->next->n = 3;
      

      由于这是重复的,你应该编写一个例程来完成这个任务:

      void append(Box* where, int what) {
       ...
      }
      

      对于清理:

      void delete(Box* where) {
       ...
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-18
        • 2015-01-23
        • 1970-01-01
        • 2015-02-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多