[英]Setting a pointer member of a structure, from a pointer to a pointer of the structure
對不起這個愚蠢的標題。
對於(非常基本的)分配的一部分,我們正在實現一個帶有指針的堆棧。 我在一小部分遇到了很多麻煩,所以我將它隔離到這個小問題中。
我將嘗試解釋我的問題,但閱讀代碼可能會更容易理解。
有一個結構(命名節點),它有 2 個成員、一個字符(命名數據)和一個指向另一個節點的指針(命名為 next)。
在主 function 內部,我有一個名為 head 的指針,它指向 node1,我想將此指針傳遞給另一個 function,並使其指向一個新節點(並使這個新節點指向另一個新節點)。 我想我可能可以將指針設置為一個新節點,但我無法正確地讓該新節點正確指向另一個新節點。
#include <stdio.h>
struct node {
char data;
struct node *next;
};
void modifyPtr(struct node **p);
int main(void)
{
/* create first 2 nodes */
struct node n1;
n1.data = '1';
struct node n2;
n2.data = '2';
/* set 1st node's next node to the 2nd node */
n1.next = &n2;
/* create a pointer to a node and make it point to the first node */
struct node *head = &n1;
/* this works as expected */
printf("1. %c\n", head->data);
printf("2. %c\n", head->next->data);
/* this should set head to a new node (which in turn points to another new node) */
modifyPtr(&head);
/* this prints as expected. Am I just lucky here? */
printf("3. %c\n", head->data);
/* but this doesn't. I want it to print 4. */
printf("4. %c\n", head->next->data);
}
void modifyPtr(struct node **p)
{
/* create node 3 and 4 */
struct node n3;
n3.data = '3';
struct node n4;
n4.data = '4';
/* set node3's next node to node4 */
n3.next = &n4;
/* make p point to node 3 */
*p = &n3;
}
我希望看到 output 為
但相反我得到
多年來,我一直試圖讓它發揮作用。 我在想這可能與在 modifyPtr 的本地 scope 中創建節點並嘗試在 main 中使用它們有關。 但是我不明白為什么#3會起作用。
有人可以告訴我我做錯了什么嗎? 謝謝。
void modifyPtr(struct node **p)
{
struct node n3;
n3.data = '3';
...
*p = &n3;
}
n3
和n4
是局部變量*,因此一旦modifyPtr
返回,它們就不再存在。 您需要在堆上分配它們。
void modifyPtr(struct node **p)
{
struct node *pn3 = malloc(sizeof(struct node));
pn3->data = '3';
...
*p = pn3;
}
你很幸運n3.data
沒有被破壞。
* - 外行人說話。
你對 scope 很感興趣。 解釋#3 的方式是,僅僅因為它有效並不意味着它總是會,也不意味着它是正確的。 是時候學習動態 memory 分配:new/delete 或 malloc/free
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.