将指针传递给函数 [英] Passing a pointer to a function

查看:161
本文介绍了将指针传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  #include< iostream> 
#include< stdlib.h>
struct node
{
int value;
node * left;
node * right;
};

void insert(node * cur,int val)
{
if(!cur)
{
cur = new node;
cur-> value = val;
cur-> left = NULL;
cur-> right = NULL;
return;
}

if(val< = cur-> value)
insert(cur-> left,val);
else
insert(cur-> right,val);
}

using namespace std;

int main()
{
node * root = NULL;


insert(root,20);
insert(root,21);

cout<<(* root).value;

返回0;
}

但我遇到问题,我的 insert() 函数很好,但是 cur 中的更改似乎没有反映到 root 指针,在insert()函数调用后, root 仍然是 NULL 。这里有什么错误?编辑:谢谢你所有的答案,使指针指针似乎是丑陋和乏味,是否有任何其他方式,还有其他一些设计吗?

解决方案

这里, root 本身已经通过值传递给 insert()。因此,从 insert(),不能更改 root 的值。换句话说, cur 对于 insert()函数是本地的。对 cur 本身进行的任何更改都不会影响传递的实际参数。



如果要更改值 root 来自 insert(),您需要将指针传递给 root from main()



要改变,你可以改变 cur insert()指向的地址。因此,按照相同的比喻,如果您更改


  1. insert(& root,20); $ li $ code> void insert(node ** cur,int val)

  2. 所有出现的 cur * cur

你应该都很好。


I was trying to implement BST using C++ , so i tried this:

    #include <iostream>
    #include <stdlib.h>
    struct node
    {
      int value;
      node* left;
      node* right;
    };

    void insert(node *cur , int val)
    {
      if(!cur)
      {
        cur = new node;
        cur->value = val;
        cur->left = NULL;
        cur->right = NULL;
        return;
      }

      if(val <= cur->value)
        insert(cur->left , val);
      else
        insert(cur->right , val);
    }

    using namespace std;

    int main()
    {
      node *root = NULL;


      insert(root , 20);
      insert(root , 21);

      cout<<(*root).value;

      return 0;
    }

but I have a problem, my insert() function works good, but the change in cur does not seem to reflect into the root pointer, as root remains NULL after the `insert() function calls. What is wrong here?

EDIT: Thanks for all your answers, making a pointer to a pointer seems to be to be ugly and tedious, is there any other way around, acheiving this with some other design?

解决方案

Here, the root itself has been passed to insert() using pass-by-value. so, from insert(), the value of root cannot be changed. In other words, the cur is local to insert() function. Any changes made to cur itself won't impact the actual argument passed.

If you want to change the value of root from insert(), you need to pass a pointer to root from main().

To elabotare, you can change the value at the address pointed by cur from insert(). So, following the same analogy, if you change

  1. insert(&root , 20);
  2. void insert(node **cur , int val)
  3. all the occurrences of cur to *cur

you should be all good to go.

这篇关于将指针传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆