[英]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.