C++ 作为双指针(**)和单指针(*)传递的参数
我一直被代码的错误弄糊涂。我创建了一个链表,并使用C++ 作为双指针(**)和单指针(*)传递的参数,c++,pointers,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()
添加元素和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;
}
当我调用printList()
函数时,什么也没发生,我想这是因为head
一直等于NULL
,但我无法找出我的代码有什么问题,假设调用push()时head
会发生变化主功能中的
和my主功能中的
如下所示:
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函数返回head指针
linkedList_t* push( linkedList_t* listHead, int new_data );
在这种情况下,反映的变化将是:-
linkedList_t *head = NULL;
head = push( head, 20 );
head = push( head, 4 );
希望我足够清楚…listHead=new\u节点
对传入此函数的调用方提供的指针没有绝对影响;因此,为什么第二个代码段不起作用。不知何故,您需要以某种方式向调用者反映列表头指针值中的任何潜在更改。这通常是通过将指针传递给指针或返回新的列表头来完成的(我有点不喜欢后者,因为它让调用者有责任记住保存返回结果)。你可能会发现一本有趣的读物,尤其是第二段。
linkedList_t *head = NULL;
head = push( head, 20 );
head = push( head, 4 );