【问题标题】:Double Pointer C for List列表的双指针 C
【发布时间】:2020-01-18 21:57:04
【问题描述】:

不久前,我开始学习 c。当我尝试编码列表时,我用双指针编写了函数,因为我在其他资源中看到了这个,然后我自己完成了这个函数并且它不起作用,请帮助我并解释它是如何工作的。

void
push(v_stack_t ** node, int num_args, ...)
{

    va_list ap;
    v_stack_t **current = node;

    va_start(ap, num_args);
    for (int i = 0; i < num_args; i++) {
        v_stack_t *new_node = (v_stack_t *) malloc(sizeof(v_stack_t));
        new_node->value = va_arg(ap, int);

        if (*current == NULL) {
            *current = new_node;
            continue;
        }
        while ((*current)->next != NULL) {
            current = &(*current)->next;
        }
        (*current)->next = new_node;
    }
    va_end(ap);
}

【问题讨论】:

  • 请解释您正在尝试做什么以及什么不起作用。您的问题是 varargs 部分(va_ 函数)还是 v_stack_t 数据结构?第二种情况,能不能展示一下那个数据结构
  • 当前之前 = &(*current)->next;我有 *current = (*current)->next;我不明白我们为什么要写这个。

标签: c list null double-pointer


【解决方案1】:

您还没有向我们展示v_stack_t 的定义,但是在分配一个之后,您并没有初始化该结构的所有成员。 new_node-&gt;next 将包含一些未知值(可能不是 NULL),当您尝试添加第二个节点时会导致问题。你应该设置

new_node->next = NULL;

就在malloc 语句之后。

不相关,您不需要从malloc 转换返回值。

【讨论】:

    【解决方案2】:

    1201ProgramAlarm 所述,您需要将 next 设置为 NULL

    但是,因为您使用current,它的最终值永远不会传播回调用方(例如,您需要在末尾设置*node)。

    您的内部while 循环可以移动到您的外部循环之上。

    而且,在开头取消引用node 并为大部分函数使用单个间接指针要容易得多。 旁注:headnode 更能描述功能。

    这是您的代码的返工:

    void
    push(v_stack_t **head, int num_args, ...)
    {
        va_list ap;
        v_stack_t *tail;
    
        // find last element of list
        tail = NULL;
        for (v_stack_t *cur = *head;  cur != NULL;  cur = cur->next)
            tail = cur;
    
        va_start(ap, num_args);
        for (int i = 0; i < num_args; i++) {
            v_stack_t *new_node = malloc(sizeof(v_stack_t));
    
            new_node->value = va_arg(ap, int);
            new_node->next = NULL;
    
            // append to tail of list
            if (tail != NULL)
                tail->next = new_node;
    
            // add node at head of list
            else
                *head = new_node;
    
            // set new element as tail of list
            tail = new_node;
        }
        va_end(ap);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-13
      • 1970-01-01
      • 2010-11-11
      • 1970-01-01
      • 2013-08-26
      • 2021-12-30
      相关资源
      最近更新 更多