【问题标题】:Why I need to add '&' when calling the function为什么我需要在调用函数时添加'&'
【发布时间】:2020-08-22 07:04:52
【问题描述】:
 typedef struct sTree {
    int key;
    struct sTree* p;
    struct sTree* left;
    struct sTree* right;
} sTree;

typedef sTree* tree;

void treeInsert(tree* root);

int main(){
    srand((unsigned)time(NULL));
    tree *root = NULL;
    treeInsert(&root);
    return 0;
}

void treeInsert(tree* root){
    ......
}

我不明白为什么在调用树插入(&root 而不是 root)时必须传递 '&'。 我创建了一个表示二叉树节点的结构,并将指向树根的指针声明为“tree*”。 所以'root'是双指针。函数“treeInsert”需要一个双指针。如果我简单地传递'root',它会使用运算符'&'获取值(NULL),否则它会正确指向根。问题是: 传递 '&root' 我没有传递三重指针?有人可以解释为什么吗?

【问题讨论】:

  • 参见Is it a good idea to typedef pointers? TL;DR — 答案是否定的,函数指针可能例外。
  • @JohnnyMopp 查看void treeInsert(tree* root) 指纹。 Typedef 与否,root 可以用于该功能。我们不知道该功能是如何实现的。让我们避免猜测。
  • @davide 编译器是否可以将&root 传递给treeInsert

标签: c pointers tree computer-science double-pointer


【解决方案1】:

关于:

treeInsert(&root);

需要&是因为函数:treeInsert()需要修改指针的内容。如果没有&,对传递的参数的任何赋值只会改变调用堆栈上的参数,而不是main()中参数的内容

关于:

tree *root = NULL;

由于tree 已经是一个指针,这导致(有效)

tree ** root = NULL;

这将无法完成所需的工作。

为什么指针不应该隐藏在typedef 语句中的一个典型例子

以下提议的代码清楚地表明了我们想要什么:

struct sTree 
{
    int key;
    struct sTree* p;
    struct sTree* left;
    struct sTree* right;
};

typedef struct sTree tree;

void treeInsert(tree** root);

int main( void )
{
    srand((unsigned)time(NULL));
    tree *root = NULL;
    treeInsert(&root);
    return 0;
}

void treeInsert(tree** root)
{
    tree *localroot = *root; // now 'localroot' is a pointer to the variable `root` in function: `main()`
    ......
}

【讨论】:

  • “由于树已经是一个指针,这导致(有效)tree ** root = NULL;。否:结果为sTree ** root = NULL
  • @RobertoCaboni,即便如此,root 不应该是main() 中的**变量
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-20
  • 2018-01-03
  • 1970-01-01
  • 2017-06-18
相关资源
最近更新 更多