c++ - pointer to pointer assignment not working if used in a separate method -



c++ - pointer to pointer assignment not working if used in a separate method -

within main, if line commented out used instead of 1 above it, lose pointer , nil gets printed console. must missing fundamental property concerning pointers thought when pass pointers x , y foo(), assignment of them work same if same logic done locally in main. missing , create assignment work correctly within foo()?

#include <cstdio> #include <cstdlib> #include <iostream> #include <string> using std::cout; using std::endl; using std::string; const int maxsize = 3; struct item{ string key; string value; }; struct node{ int count; item *item[maxsize + 1]; node *branch[maxsize + 1]; }; void foo(item *x, item*y) { y = x; } int main(int argc, char *argv[]) { item *x = new item(); x->key = "hi"; x->value = "there"; item *y = new item(); y = x; //foo(x, y); node *p = new node(); p->item[1] = y; cout << p->item[1]->key << " " << p->item[1]->value << endl; homecoming 0; }

your main question like: "how can move code function , same behaviour?"

inside main have y=x. before describing how move logic function, should line unusual , doesn't want do.

but, i'll ignore , pretend y=x in main 'correct' , want move code function. right way in c++ move code functions, without changing behaviour, utilize references.

for example, if had

int main() { int = 3; int b= 0; b = a; }

you same behaviour:

void foo(int &a, int &b) { b = a; } int main() { int = 3; int b= 0; foo(a,b); }

it should noted names of variables meaningless. write foo follows , identical.

void foo(int &left, int &right) { right = left; }

anyway, re-create , paste code function , create parameters references. in case, simply

void foo(item *(&x), item*(&y)) { y = x; // same y=x in main, because x , y references here }

sometimes, language can confusing regarding placement of * , &, simplest way turn parameter x reference set ( ) around , set & within ( ). i.e. x becomes (&x).

c++ pointers

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -