[英]What is the difference between address of pointer and double pointer
I have this simple code of node.c :我有这个简单的node.c代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int x;
struct Node *next;
} Node;
void unshift(Node **root, int value)
{
Node *newNode = malloc(sizeof(Node));
newNode->x = value;
newNode->next = *root;
*root = newNode;
}
//doesn't work if address of pointer is passed to unshift()
void foo(Node *root)
{
if (root == NULL)
{
//pass address of pointer
unshift(&root, 4);
}
}
//works with double pointer passed to unshift()
void bar(Node **root)
{
if (*root == NULL)
{
//pass double pointer
unshift(root, 4);
}
}
int main()
{
Node *root = NULL;
//works
// bar(&root);
// printf("%p\n", root);
//does not work
foo(root);
printf("%p\n", root);
}
Now there is a function insert(Node **root, int value)
, which takes double pointer to root in order to change it (the newly created node will itself become a root).现在有一个 function
insert(Node **root, int value)
,它采用指向根的双指针来更改它(新创建的节点本身将成为根)。 So obviously I can pass type Node **
either way -> double pointer, or address of pointer.所以很明显,我可以通过任何一种方式传递类型
Node **
-> 双指针或指针地址。 I do so in 2 separate function -> foo(Node*)
and bar(Node**)
.我在 2 个单独的 function ->
foo(Node*)
和bar(Node**)
中这样做。 In foo I am thus passing address of the argument whereas in bar I simply pass its argument.因此,在 foo 中,我传递了参数的地址,而在 bar 中,我只是传递了它的参数。
The issue is, only the bar()
with double pointer will actually change the root pointer from main.问题是,只有带有双指针的
bar()
实际上会从 main更改根指针。 The foo()
function will not, even if passing the right datatype. foo()
function 不会,即使传递了正确的数据类型。 That is, after call with foo()
, the pointer root is nil
(still null pointer as in declaration), whereas after bar()
the pointer really changed
.也就是说,在使用
foo()
调用之后,指针根为nil
(仍然是 null 指针,如声明中的那样),而在bar()
之后,指针真的changed
。 So why does compiler treats the addressof and pointer differently even though both are passing the same data?那么为什么编译器会以不同的方式处理地址和指针,即使它们都传递相同的数据呢? And why does not
foo()
also change the root pointer?为什么
foo()
也不改变根指针?
It is not "the same data".它不是“相同的数据”。 In
foo
, &root
is the address of the formal argument root
in foo
, but in bar
you are passing the address of the variable from main
.在
foo
中, &root
是foo
中形式参数root
的地址,但在bar
中,您是从main
传递变量的地址。 In other words, the value is changed in foo
but that change is lost when foo
returns because it did not update the value in main
.换句话说,
foo
中的值发生了更改,但是当foo
返回时,该更改丢失了,因为它没有更新main
中的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.