c++ - assign an address to the Node* in link list? -


   structure of node     typedef struct node{     int x;     node* next;   };    // in main() can make head pointer,and assign null i-e        node* start_pointer=null;  //this line in main() function                             // , consider head pointer      void add_node(node* start_pointer){  node first; cout<<"enter value of x\n "; cin>>first.x; if (start_pointer==null){     start_pointer=&first;   //try assign address of object of pointer     first.next=null;     }   else {                                   node* temp=start_pointer;     while (temp->next != null){         //program break @ stage           temp=temp->next;}      temp->next=first.next;                     first.next=null;  } 

i assigning address node* , try catch '->' operator ok ? every time when run add_node function execute unfortunately not go else condition

there 2 different things wrong code

firstly must allocate new nodes in add_node, not take address of local variable.

instead of this

start_pointer=&first; first.next=null; 

you should have this

start_pointer=new node; start_pointer->next=null; 

taking address of first wrong because first gets destroyed when exit function. start_pointer pointing @ object has been destroyed , program crash. objects allocated new live until delete them.

second error function changes start_pointer in add_node function. not change start_pointer in main function. these 2 variables might have same name different variables. why code never enters else part of add_node. change start_pointer in main need change add_node function use reference adding & after type.

void add_node(node*& start_pointer){ // use reference 

now start_pointer in add_node reference start_pointer in main , changes start_pointer in add_node affect start_pointer in main.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -