c - 为什么我们这里使用 "&"(: insert(&(*root)->left,值);但我们这里不使用 "&": search(root->left,值);

标签 c pointers tree double binary-tree

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

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

为什么我们使用&这里:insert(&(*root)->left,value);但我们不使用&这里:search(root->left, value);

最佳答案

这是在 C 中引入引用的一种方法。在第一种情况下,函数 insert 可以更改指针 left 如果它将像函数 serach 中那样按值传递> 那么函数insert的任何参数的改变都不会应用到原来的指针上。因此,该函数“通过引用”接受参数。

在第二种情况下,当使用函数搜索时,左指针不会改变。

考虑下面的例子会更清楚

#include <stdio.h>
#include <stdlib.h>

void f( char **p )
{
   free( *p );
   *p = ( char * )malloc( sizeof( char ) );
   **p = 'B';
}

void g( char *p )
{
   printf( "%c\n", *p );
}

int main()
{
   char *p = ( char * )malloc( sizeof( char ) );
   *p = 'A';

   g( p );

   f( &p );

   g( p );

   free( p );
}

如果函数 f 不接受“通过引用”的指针,则原始点的值不会改变。

考虑修改后的代码并比较其执行结果

#include <stdio.h>
#include <stdlib.h>

void f( char *p )
{
   free( p ); // OOPS! memory was freed
   p = ( char * )malloc( sizeof( char ) );
   *p = 'B';
}

void g( char *p )
{
   printf( "%c\n", *p );
}

int main()
{
   char *p = ( char * )malloc( sizeof( char ) );
   *p = 'A';

   g( p );

   f( p ); // after the call the program behaviour is undefined.

   g( p );

   free( p );
}

关于c - 为什么我们这里使用 "&"(: insert(&(*root)->left,值);但我们这里不使用 "&": search(root->left,值);,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25045118/

相关文章:

c - PostgreSQL自定义C函数导入失败: "sprintf_chk: symbol not found"

c++ - 非 GPL XMPP 客户端库

c - 类型 "char *"和类型 "char[10]"之间的区别

javascript - 从 json 数据创建基于 div 的树布局

JAVA,NodeSet转换为XML,解析将其插入树中

c - 引用和取消引用指针

c - 什么时候会使用 malloc 而不是 zmalloc?

C++ - 获取特定内存地址的值

C++ new * char 不为空

recursion - 关于这个 "flatten the nested list"问题,这本书的答题卡是不是错了?