简体   繁体   English

列表的双指针 C

[英]Double Pointer C for List

A short time ago I began to learn c.不久前我开始学习c。 When I tried coding list I wrote function with double pointer because I saw this in other resource, then I by myself finished writing this function and it's didn't work, please help me and explain how this work.当我尝试编码列表时,我用双指针编写了函数,因为我在其他资源中看到了这一点,然后我自己完成了这个函数,但它不起作用,请帮助我并解释它是如何工作的。

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);
}

You haven't shown us the definition for v_stack_t , but you do not initialize all the members of that struct after you allocate one.您还没有向我们展示v_stack_t的定义,但是您没有在分配一个结构体之后初始化该结构体的所有成员。 new_node->next will have some unknown value in it (likely not NULL), causing problems when you try to add a second node. new_node->next将包含一些未知值(可能不是 NULL),当您尝试添加第二个节点时会导致问题。 You should set你应该设置

new_node->next = NULL;

right after the malloc statement.malloc语句之后。

Unrelated, you don't need to cast the return value from malloc .无关,您不需要从malloc返回值。

As 1201ProgramAlarm mentioned, you need to set next to NULL .正如1201ProgramAlarm提到的,您需要在NULL next设置。

But, because you use current , its final value is never propagated back to caller (eg you'd need to set *node at the end).但是,因为您使用current ,它的最终值永远不会传播回调用者(例如,您需要在最后设置*node )。

Your inner while loop could be moved above your outer loop.您的内部while循环可以移动到您的外部循环之上。

And, it's far easier to dereference node at the beginning and use single indirect pointers for the bulk of the function.而且,在开始时取消引用node并为大部分函数使用单个间接指针要容易得多。 Side note: head is more descriptive of function than node here.旁注:这里的headnode更能描述功能。

Here's a rework of your code:这是您的代码的返工:

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM