Problem with pointer and variable

Posting a fast question for the experienced guys:

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...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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;
       }
     else if((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;
       }
     else if((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...


Thanks in advance
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.
Topic archived. No new replies allowed.