c++ - About reference to pointers -
i've been making tree, because planting trees save planet (or program).
class tree { node* root; // ... void insert(int value){ private_insert(value, root); } void insert_private(int value, node* n){ if(n == nullptr){ n = new node(value); } else { standard recursive insertion function here } } // ... };
long story short i've tried using shared_ptrs first, the insert() function never add element tree. thought might doing wrong shareds tried raw pointers , got same non-inserty resoults.
turns out need pass reference root/nodes.
void insert_private(int value, node*& n) {...};
i understand if dont pass reference copy made. if pointer holds address, doesnt it's copy hold same address? if make new() non-referenced pointer why doesnt stick root/nodes?
the why question here, can accept it works this, tree works, dont know why this.
edit: after reading comments created small expert level program:
void fn(int* i){ cout << "address of local in fn before change: " << << endl; = new int(2); // here made new int, , address of // integer , point there, passed on before // becomes irrelevant cout << "address of local in fn after change: " << << endl; } void fn2(int **i){ cout << "address of local in fn2 before change: " << << endl; *i = new int(2); cout << "address of local in fn2 after change: " << << endl; } int main(){ int* p = nullptr; cout << "address of p: " << p << endl; fn(p); cout << "p& is: " << &p << endl; fn2(&p); cin.get(); return 0; };
thank you, everyone, answers, helped lot. random.org determine who's 1 approved answer thing.
yes it's copy , holds same address, assigning copy thrown away when function returns. original unaltered. that's problem.
as aside, imho, if altering value of parameter, should use pointer, hence pointer pointer in case. makes more obvious reader you're changing value.
Comments
Post a Comment