// void insert_start(struct node *head, int data)
// {
// struct node *ptr = (struct node *)malloc(sizeof(struct node));
// ptr->next_ptr = head;
// ptr->data = data;
// head=ptr;
// }
上面的功能不起作用,而下面的功能起作用
struct node *insert_start(struct node *head, int data)
{
struct node *ptr = (struct node *)malloc(sizeof(struct node));
ptr->next_ptr = head;
ptr->data = data;
return ptr;
}
uj5u.com熱心網友回復:
看到你的問題如下,在注釋代碼中,當你將呼叫的指標傳遞head給你的函式時,將創建另一個指向相同地址的指標,但是你不能改變你的 main 中的原始指標指向什么,就像在下一張圖片中:

如果您想更改 main 函式中的指標指向的內容,則必須將指標傳遞給該指標以更改其指向的內容,如下圖所示:

為了做到這一點,你可以修改你的評論功能如下:
void insert_start(struct node **head, int data)
{
struct node *ptr = (struct node *)malloc(sizeof(struct node));
ptr->next_ptr = *head;
ptr->data = data;
*head = ptr;
}
并在您呼叫該函式時的主函式中,將指標的地址傳遞給它以更改它指向的內容:insert_start(&head, data);
uj5u.com熱心網友回復:
這兩個函式都宣告為
void insert_start(struct node *head, int data);
處理指向用作引數運算式的頭節點的指標的值的副本。
因此,在函式中更改副本不會影響原始指標的值。它保持不變。
函式之間的唯一區別是,第二個函式將原始指標副本的修改值回傳給呼叫者,該副本指向頭節點。因此,將函式的回傳值分配給指向頭節點的原始指標,您可以更新其值。
uj5u.com熱心網友回復:
關于您的第一個(注釋)示例...
如注釋中所述,C 按值傳遞引數。
在 C 中,如果要更改變數的值,則必須傳遞該變數的地址,而不是變數本身。
所以在你原來的功能中:
void insert_start(struct node *head, int data)
{
struct node *ptr = (struct node *)malloc(sizeof(struct node));
ptr->next_ptr = head;
ptr->data = data;
head=ptr;
}
*head包含 的實體的地址值struct node。因此,head退貨時不會更改。
如果您想使用一種形式的void函式來修改引數以允許它更改包含在 中的地址*head,那么您必須傳遞它的地址: **head。然后在函式體中,進行如下修改。(注意原因演員已被洗掉。)
void insert_start(struct node **head, int data)
{
struct node *ptr = malloc(sizeof(*ptr));
if(ptr)//verify return of malloc before using
{
ptr->data = data;
ptr->next_ptr = (*head);
(*head) = ptr;//setting head to address of new node
}
}
呼叫示例:(在函式中呼叫,例如main())
struct node *new;
insert_start(&new, 10);//passing address of *new
if(!new)
{
//handle error
}
....
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/507322.html
上一篇:C中一流的鏈表實作的問題
下一篇:C中結構的未宣告識別符號錯誤
