c++ - 作为双指针 (**) 和单指针 (*) 传递的参数

标签 c++ pointers

我一直对我的代码错误感到困惑。我创建了一个链表并使用 push() 添加元素并使用 printList() 输出元素,下面的代码工作正常。

#include <stdio.h>
#include <stdlib.h>
struct linkedList {
    int         _Value;
    struct linkedList   * _Next;
};
typedef  struct linkedList linkedList_t;

/* Function to push a node */
void push( linkedList_t** listHead, int new_data )
{
    /* allocate node */
    linkedList_t* new_node =
        (linkedList_t *) malloc( sizeof(linkedList_t) );

    /* put in the data  */
    new_node->_Value = new_data;

    /* link the old list off the new node */
    new_node->_Next = *listHead;

    /* move the head to point to the new node */
    *listHead = new_node;
}


/* Function to print linked list */
void printList( linkedList_t *head )
{
    linkedList_t *tmp = head;
    while ( tmp != NULL )
    {
        printf( "%d  ", tmp->_Value );
        tmp = tmp->_Next;
    }
}
int main( int argc, char* argv[] )
{  
    linkedList_t *head = NULL;
    push( &head, 20 );
    push( &head, 4 );
    push( &head, 15 );
    push( &head, 85 );
    printList( head );
    return 0;
    }

问题是,当我将参数更改为单指针时,例如:

 void push( linkedList_t* listHead, int new_data )
{
    /* allocate node */
    linkedList_t* new_node =
        (linkedList_t *) malloc( sizeof(linkedList_t) );

    /* put in the data  */
    new_node->_Value = new_data;

    /* link the old list off the new node */
    new_node->_Next = listHead;

    /* move the head to point to the new node */
    listHead = new_node;
}

当我调用 printList() 函数时,没有任何反应,我认为这是因为 head 一直等于 NULL 但我不能找出我的代码有什么问题,假设当我在 main 函数 和我的 中调用 push()head 将被更改主要功能如下:

int main( int argc, char* argv[])
{  
    linkedList_t *head = NULL;
    push( head, 20 );
    push( head, 4 );
    push( head, 15 );
    push( head, 85 );
    printList( head );
    return 0;
    }

我需要一些建议。有人帮忙吗?谢谢!

最佳答案

当你使用单指针时,你实际上传递的是头指针的拷贝。在双指针的情况下,您传递的是头指针的地址,以便对其进行更改。

您可以通过微小的更改使代码与单指针版本一起工作。在这种情况下,您需要从推送函数返回头指针。

linkedList_t* push( linkedList_t* listHead, int new_data );

在那种情况下,反射(reflect)的变化将是:-

linkedList_t *head = NULL;
head  = push( head, 20 );
head = push( head, 4 );

希望我已经足够清楚了...

关于c++ - 作为双指针 (**) 和单指针 (*) 传递的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26880602/

相关文章:

c - _PTR_ 背后的基本原理是什么?

c++ - Eclipse反汇编 View ,可以在不调试程序的情况下查看反汇编吗?

c++ - 在 C++ 中调整动态数组的大小

具有多个类的 C++ 共享库

Javascript:创建窗口的假副本以通过引用传递函数

c++ - 这是一个真正的问题 : warning C4172: returning address of local variable or temporary

c++ - 在 reinterpret_cast-ing 之后通过父指针调用 delete 时内存是否泄漏?

c++ - 如何在 C++ 中将 fork() 转换为 Pthread (Linux)

c++ - 使用 `delete` 从链表中删除节点

c++ - 使用 Qt : Invalid conversion from const void* to void* while using QList<Type *const>