c++ - pointer problems with function calls -


i’m working on beginner(!) exercise.

i comfortable passing basic variables , using &variable parameters can make changes variable not destroyed when returning. still learning pointers. working on basic mutant bunny exercise (linked list practice).

in create linked list declaring class bunny. set expect data section , ‘next’ pointer set linkage.

struct bunny {     string name;     int age;     // more variables here     bunny* next; }; 

everything works great when call function things create bunnies using function:

bunny* add_node ( bunny* in_root ){} 

this sets node , returns want. can things call function modify bunny class aging bunnies.

void advanceage ( bunny* in_root ){} 

i pass in head , can modify bunnies in called function , stays modified when goes main. example can use:

in_root->age ++;  

in called function , when return ‘main’ still changed. can use -> in called function , makes change permanently. think because pointer dereferenced(?) -> still getting head around it...

so far good.

the problem comes when want call function delete list. (nuclear option… no more bunnies)

i can delete nodes in called function… not change bunny in ‘main’. example… not permanently remove node.

void deathcheck(bunny* in_root){     bunny* prev_ptr;     prev_ptr = in_root;     if (prev_ptr == null){         cout << "no list check age." << endl; return;     } else {         prev_ptr = null;   // <- code have stick?      return;}  // rest of deathcheck 

i’m curious if there way set node null in called function , have stick?

since you're passing in_root value, there's no way modify caller's variable. pass reference.

void deathcheck(bunny* &in_root) {     bunny *prev_ptr = in_root;     ...     in_root = nullptr;     return; } 

Comments