简体   繁体   English

当指向结构的双指针是函数的参数时,为什么我们使用“&(*”语句?

[英]Why we use “&(*” statement when double pointer to struct is an argument of a function?

void instert(NODE**root, int value)
{
    ...
    insert(&(*root)->left,value);
    ...
}

void search(NODE*root, int value)
{
    ...
    search(root->left, value);
    ...
}

Why we use "&" here: insert(&(*root)->left,value); 为什么在这里使用“&”:insert(&(* root)-> left,value); But we do not use "&" here: search(root->left, value); 但是我们在这里不使用“&”:search(root-> left,value);

The expression: 表达方式:

*root->left

Is equivalent to: 等效于:

*(root->left)

Due to operator precedence. 由于操作员优先。

So you need: 因此,您需要:

(*root)->left

If you want the left member that *root points to. 如果要*root指向的left成员。

And then: 接着:

&(*root)->left

Is the pointer to the left member of *root , which is then of type NODE ** , what the insert function requires. 是指向*root left成员的指针,后者的类型为NODE ** ,这是insert函数所需的。

An extra level of indirection is added to insert function so that it could modify the pointer. 附加级别的间接添加到insert函数,以便它可以修改指针。 This is not necessary in case of the search function, because it never modifies the pointer passed to it. 对于search功能,这是没有必要的,因为它永远不会修改传递给它的指针。

Specifically, there needs to be a place in the insert function that does something like this: 具体来说,在insert函数中需要有一个类似以下内容的位置:

*root = malloc(sizeof(NODE));
(*root)->left = NULL;
(*root)->right = NULL;
(*root)->value = value;

This would modify the pointer which is pointed to by the pointer to pointer. 这将修改指针指向的指针所指向的指针。

Note that it is possible to avoid this extra level of indirection by returning the new value of the pointer from insert , like this: 请注意,可以通过从insert返回指针的新值来避免这种额外的间接级别,如下所示:

NODE* insert(NODE*root, int value) {
    ...
    root->left = insert(root->left, value);
    ...
}

However, this changes the way in which all callers must call insert , including the top-level caller: rather than writing 但是,这改变了所有调用者必须调用insert ,包括顶级调用者:而不是编写

insert(&root, value);

he would be forced to write 他将被迫写

root = insert(root, value);

&(* isn't a statement. &(*不是陈述。

It is parts of the & -operator being applied to the expression (*root)->left . 它是& (*root)->left运算符应用于表达式(*root)->left

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM