本文介绍了当指向结构的双指针是函数的参数时,为什么我们使用“&(*"语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我们为什么使用&"这里:插入(&(*root)->左,值);但是我们不使用&"这里:搜索(根->左,值);

Why we use "&" here: insert(&(*root)->left,value);But we do not use "&" here: search(root->left, value);

推荐答案

insert 函数添加了一个额外的间接级别,以便它可以修改指针.对于 search 函数,这不是必需的,因为它从不修改传递给它的指针.

An extra level of indirection is added to insert function so that it could modify the pointer. This is not necessary in case of the search function, because it never modifies the pointer passed to it.

具体来说,insert 函数中需要有一个地方可以做这样的事情:

Specifically, there needs to be a place in the insert function that does something like this:

*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.

请注意,可以通过从 insert 返回指针的新值来避免这种额外的间接级别,如下所示:

Note that it is possible to avoid this extra level of indirection by returning the new value of the pointer from insert, like this:

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

然而,这改变了所有调用者必须调用insert的方式,包括顶级调用者:而不是写

However, this changes the way in which all callers must call insert, including the top-level caller: rather than writing

insert(&root, value);

他会被迫写作

root = insert(root, value);

这篇关于当指向结构的双指针是函数的参数时,为什么我们使用“&(*"语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 07:50
查看更多