I have a pointer that points to a variable (of struct type). All of this is in a loop and i just found out that every time the loop repeats the code and the variable changes value (contains a new instance of the struct), the pointer changes too (obviously). The thing is that it is a head_ptr for a doubly linked list and although i want it to point at the first item of the list, I do not want it to change afterwards except if it enters a specific function...
void insert_entry(PENTRY head_ptr){
ENTRY entry;
PENTRY en_cur;
char c;
do{
entry=give_entry(); //MEGA MISTAKE! GIVING A NEW VALUE WILL ALSO CHANGE THE VALUE OF HEAD_PTR SINCE IT POINTS TO THE SAME VARIABLE!
if(head_ptr==NULL){ //Inserts first element in list
head_ptr=&entry;
entry.prev=NULL;
}
if(entry.am < (head_ptr->am)){ //Inserts element in first place if it has to be sorted so
entry.next=head_ptr;
head_ptr->prev=&entry;
entry.prev=NULL;
head_ptr=&entry;
}
en_cur=head_ptr;
while((en_cur->next!=NULL)&&(en_cur->am < entry.am)){ //Bgainei apo to loop an ftasei sto last stoixeio
en_cur=en_cur->next; //i brei kapoio megalytero tou entry pou balame
puts("TEST");
}
if((en_cur->next==NULL) && (en_cur->am < entry.am)){
en_cur->next=&entry;
entry.next=NULL;
entry.prev=en_cur;
}
elseif((en_cur->next==NULL) && (en_cur->am > entry.am)){
en_cur->prev->next=&entry;
entry.prev=en_cur->prev;
entry.next=en_cur;
en_cur->prev=&entry;
}
elseif((en_cur->next!=NULL) && (en_cur->am > entry.am)){
en_cur->prev->next=&entry;
entry.prev=en_cur->prev;
entry.next=en_cur;
en_cur->prev=&entry;
}
puts("More? y/n");
scanf("%c", &c);
getchar();
}while(c=='y');
}
This is the code for better understanding. Every time the give_entry gets called the entry variable changes struct instance and so does the head_ptr but this messes up everything else... I'm pretty sure i can find a way around this problem but I'd like an experienced advice cause many of my solutions have been accused of being sloppy...
You should pass PENTRY head_ptr either through poinetr or as a reference. Otherwise in your declaration of function void insert_entry(PENTRY head_ptr); head_ptr is a local variable and all changes to it will be discarded after exiting the function.