这个 struct node **p 在做什么?
what does this struct node **p is doing?
我正在学习数据结构,这里有一个我无法理解的东西...
int end(struct node** p, int data){
/*
This is another layer of indirection.
Why is the second construct necessary?
Well, if I want to modify something allocated outside of my function scope,
I need a pointer to its memory location.
*/
struct node* new = (struct node*)malloc(sizeof(struct node));
struct node* last = *p;
new->data = data;
new->next = NULL;
while(last->next !=NULL){
last = last ->next ;
}
last->next = new;
}
- 为什么我们要使用 struct node **p?
- 我们可以使用 struct node *p 代替 struct node **p 吗?
我在这里写的评论是我在这里找到的答案,但是,我仍然不清楚这是完整的代码...
请帮帮我
谢谢
显示的函数(根据其名称)应创建一个新节点并将其附加到列表的末尾,该列表由指向该列表节点的指针的指针表示。 (但是我怀疑它是否确实如此,同意评论...)
由于列表可能为空并且指向节点的指针因此不指向现有节点,因此有必要能够潜在地将指向该列表的第一个元素的指针从 NULL 更改为指向新创建的节点。
只有当参数不仅是指向第一个节点的指针的副本而且是指向第一个节点的指针的指针时才有可能。因为在第二种情况下,您可以取消引用指向指针的指针并实际修改指向节点的指针。
否则函数调用后列表(如果为 NULL)将始终指向 NULL。
简答:发布的代码中不需要双指针。
传递双指针的正常原因是您希望能够在调用方范围内更改变量的值。
示例:
struct node* head = NULL;
end(&head, 42);
// Here the value of head is not NULL any more
// It's value was change by the function end
// Now it points to the first (and only) element of the list
并且您的函数应包含如下一行:
if (*p == NULL) {*p = new; return 0;}
但是,您的代码没有!也许这真的是您代码中的错误?
由于您的代码没有更新*p
,因此没有理由传递双指针。
顺便说一句:您的函数说它将 return int
但代码没有 return
语句。这肯定是一个错误。
我正在学习数据结构,这里有一个我无法理解的东西...
int end(struct node** p, int data){
/*
This is another layer of indirection.
Why is the second construct necessary?
Well, if I want to modify something allocated outside of my function scope,
I need a pointer to its memory location.
*/
struct node* new = (struct node*)malloc(sizeof(struct node));
struct node* last = *p;
new->data = data;
new->next = NULL;
while(last->next !=NULL){
last = last ->next ;
}
last->next = new;
}
- 为什么我们要使用 struct node **p?
- 我们可以使用 struct node *p 代替 struct node **p 吗? 我在这里写的评论是我在这里找到的答案,但是,我仍然不清楚这是完整的代码...
请帮帮我 谢谢
显示的函数(根据其名称)应创建一个新节点并将其附加到列表的末尾,该列表由指向该列表节点的指针的指针表示。 (但是我怀疑它是否确实如此,同意评论...)
由于列表可能为空并且指向节点的指针因此不指向现有节点,因此有必要能够潜在地将指向该列表的第一个元素的指针从 NULL 更改为指向新创建的节点。
只有当参数不仅是指向第一个节点的指针的副本而且是指向第一个节点的指针的指针时才有可能。因为在第二种情况下,您可以取消引用指向指针的指针并实际修改指向节点的指针。
否则函数调用后列表(如果为 NULL)将始终指向 NULL。
简答:发布的代码中不需要双指针。
传递双指针的正常原因是您希望能够在调用方范围内更改变量的值。
示例:
struct node* head = NULL;
end(&head, 42);
// Here the value of head is not NULL any more
// It's value was change by the function end
// Now it points to the first (and only) element of the list
并且您的函数应包含如下一行:
if (*p == NULL) {*p = new; return 0;}
但是,您的代码没有!也许这真的是您代码中的错误?
由于您的代码没有更新*p
,因此没有理由传递双指针。
顺便说一句:您的函数说它将 return int
但代码没有 return
语句。这肯定是一个错误。