Edit where a pointer points within a function

后端 未结 3 1202
温柔的废话
温柔的废话 2021-01-01 01:42

I have a pointer to a struct object in C++.

 node *d=head;

I want to pass that pointer into a function by reference and edit where it point

相关标签:
3条回答
  • 2021-01-01 02:21

    Pass it by reference:

    void foo(node*& headptr)
    {
         // change it
         headptr = new node("bla");
         // beware of memory leaks :)
    }
    
    0 讨论(0)
  • 2021-01-01 02:37

    You have two basic choices: Pass by pointer or pass by reference. Passing by pointer requires using a pointer to a pointer:

    void modify_pointer(node **p) {
        *p = new_value;
    }
    
    modify_pointer(&d);
    

    Passing by reference uses &:

    void modify_pointer(node *&p) {
        p = new_value;
    }
    
    modify_pointer(d);
    

    If you pass the pointer as just node *d, then modifying d within the function will only modify the local copy, as you observed.

    0 讨论(0)
  • 2021-01-01 02:42

    Pass a node ** as an argument to your function:

    // f1 :
    node *d = head;
    
    f2(&d);
    
    // f2:
    void f2(node **victim) {
        //assign to "*victim"
    }
    
    0 讨论(0)
提交回复
热议问题