草庐IT

c++ - 指针 - 将 ptr 传递给 ptr 或传递 ptr 的地址

coder 2024-02-26 原文

我正在尝试使用两种方法删除示例二叉搜索树的左子节点 (10):

  • 方法 1:通过将指针传递给指向当前节点的指针。
  • 方法2:通过将指针的地址传递给当前节点。这不会删除节点,但调用 delete 会破坏指针排列,导致打印节点时发生崩溃。

树看起来像这样,我正在尝试删除 10 并用 5 替换它

       20
       |  
   10--|---30
    |
5---|

我对指针有一些了解。但是,我仍然不清楚指针的这种行为。

#include <iostream>
class Node
{
public:
    Node(int key) : leftChild(0), rightChild(0), m_key (key){}
    ~Node(){}

    Node *leftChild;
    Node *rightChild;
    int m_key;
};

Node* build1234(int, int, int, int);
void print(Node *);
void print1234(Node *);

void removeLeft(Node **nodePtr)
{
    Node *oldPtr = *nodePtr;
    if(*nodePtr)
    {
        *nodePtr = (*nodePtr)->leftChild;
        delete oldPtr;
    }
}

int main()
{
    Node *demo1 = build1234(10, 20, 30, 5);
    Node *demo2 = build1234(10, 20, 30, 5);
    print1234(demo1);
    print1234(demo2);

    //Method1 - 10 is correctly removed with 5
    Node **nodePtr = &demo1;
    nodePtr = &(*nodePtr)->leftChild;
    removeLeft(nodePtr);
    print1234(demo1);

    //Method2 - 10 is not removed
    Node *node = demo2;
    node = node->leftChild;
    removeLeft(&node);
    print1234(demo2);       
    return 0;
}

Node* build1234(int B, int A, int C, int D)
{
    Node *root = new Node(A);
    root->leftChild = new Node(B);
    root->rightChild = new Node(C);
    root->leftChild->leftChild = new Node(D);
    return root;
}
void print(Node *node)
{
    if(node)
    {
        print(node->leftChild);
        std::cout << "[" << node->m_key << "]";
        print(node->rightChild);
    }
}

void print1234(Node *node)
{
    std::cout << std::endl;
    print(node);
}

注意:这道题不是BST,而是指针。如果您在 main() 函数中看到对 removeLeft(nodePtr)removeLeft(&node) 的两次调用。

  1. 这两者有何不同?
  2. 为什么第二种方法达不到预期的效果?

最佳答案

在第一种情况下,您传递的是树中存在的指针的地址,因此您是在直接修改树的内容。

在第二种情况下,您传递的是 main() 局部变量的地址。树没有修改,从地址删除是访问栈内存,所以崩溃

关于c++ - 指针 - 将 ptr 传递给 ptr 或传递 ptr 的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7945585/

有关c++ - 指针 - 将 ptr 传递给 ptr 或传递 ptr 的地址的更多相关文章

  1. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  2. ruby - 从 Ruby 中的主机名获取 IP 地址 - 2

    我有一个存储主机名的Ruby数组server_names。如果我打印出来,它看起来像这样:["hostname.abc.com","hostname2.abc.com","hostname3.abc.com"]相当标准。我想要做的是获取这些服务器的IP(可能将它们存储在另一个变量中)。看起来IPSocket类可以做到这一点,但我不确定如何使用IPSocket类遍历它。如果它只是尝试像这样打印出IP:server_names.eachdo|name|IPSocket::getaddress(name)pnameend它提示我没有提供服务器名称。这是语法问题还是我没有正确使用类?输出:ge

  3. ruby - rails 3 redirect_to 将参数传递给命名路由 - 2

    我没有找到太多关于如何执行此操作的信息,尽管有很多关于如何使用像这样的redirect_to将参数传递给重定向的建议:action=>'something',:controller=>'something'在我的应用程序中,我在路由文件中有以下内容match'profile'=>'User#show'我的表演Action是这样的defshow@user=User.find(params[:user])@title=@user.first_nameend重定向发生在同一个用户Controller中,就像这样defregister@title="Registration"@user=Use

  4. ruby-on-rails - 如何生成传递一些自定义参数的 `link_to` URL? - 2

    我正在使用RubyonRails3.0.9,我想生成一个传递一些自定义参数的link_toURL。也就是说,有一个articles_path(www.my_web_site_name.com/articles)我想生成如下内容:link_to'Samplelinktitle',...#HereIshouldimplementthecode#=>'http://www.my_web_site_name.com/articles?param1=value1¶m2=value2&...我如何编写link_to语句“alàRubyonRailsWay”以实现该目的?如果我想通过传递一些

  5. ruby - 在 Ruby 中按名称传递函数 - 2

    如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只

  6. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

  7. ruby - 如何计算 Liquid 中的变量 +1 - 2

    我对如何计算通过{%assignvar=0%}赋值的变量加一完全感到困惑。这应该是最简单的任务。到目前为止,这是我尝试过的:{%assignamount=0%}{%forvariantinproduct.variants%}{%assignamount=amount+1%}{%endfor%}Amount:{{amount}}结果总是0。也许我忽略了一些明显的东西。也许有更好的方法。我想要存档的只是获取运行的迭代次数。 最佳答案 因为{{incrementamount}}将输出您的变量值并且不会影响{%assign%}定义的变量,我

  8. ruby - 如何将 Puma::Configuration 传递给 Sinatra? - 2

    这是我的网络应用:classFront我是这样开始的(请不要建议使用Rack):Front.start!这是我的Puma配置对象,我不知道如何传递给它:require'puma/configuration'Puma::Configuration.new({log_requests:true,debug:true})说真的,怎么样? 最佳答案 配置与您运行的方式紧密相关puma服务器。运行的标准方式puma-pumaCLI命令。为了配置puma配置文件config/puma.rb或config/puma/.rb应该提供(参见examp

  9. jquery - 如何将 AJAX 变量从 jQuery 传递到他们的 Controller ? - 2

    我有一个电子邮件表格。但是我正在制作一个测试电子邮件表单,用户可以在其中添加一个唯一的电子邮件,并让电子邮件测试将其发送到该特定电子邮件。为了简单起见,我决定让测试电子邮件通过ajax执行,并将整个内容粘贴到另一个电子邮件表单中。我不知道如何将变量从我的HAML发送到我的Controllernew.html.haml-form_tagadmin_email_blast_pathdoSubject%br=text_field_tag'subject',:class=>"mass_email_subject"%brBody%br=text_area_tag'message','',:nam

  10. arrays - Ruby 数组 += vs 推送 - 2

    我有一个数组数组,想将元素附加到子数组。+=做我想做的,但我想了解为什么push不做。我期望的行为(并与+=一起工作):b=Array.new(3,[])b[0]+=["apple"]b[1]+=["orange"]b[2]+=["frog"]b=>[["苹果"],["橙子"],["Frog"]]通过推送,我将推送的元素附加到每个子数组(为什么?):a=Array.new(3,[])a[0].push("apple")a[1].push("orange")a[2].push("frog")a=>[[“苹果”、“橙子”、“Frog”]、[“苹果”、“橙子”、“Frog”]、[“苹果”、“

随机推荐