繁体   English   中英

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

[英]Arguments passing as double pointer(**) and single pointer(*)

我一直对代码的错误感到困惑。 我创建了一个链表,并使用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 function调用push()时, head将被更改。我的main function如下:

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

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

当您使用单个指针时,实际上是在传递头部指针的副本。 在使用双指针的情况下,您要传递头指针的地址,以便对其进行更改才有意义。

您可以更改代码,使其与单指针版本一起使用。 在这种情况下,您需要从push函数返回头指针。

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

在这种情况下,反映的变化将是:

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

希望我足够清楚...

暂无
暂无

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

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