Hey guys!
I'm learning now the linked lists subject.
I wrote program which gets phone numbers and names and stores them in a two-way-linked list (a linked list with pointers both to the next node and to the previous, which allows you to go back and forth).
The struct itself is called "phone" and declared like this:
Code:
struct phone {
int num;
char name[20];
struct phone *prv;
struct phone *nxt;
};
I declared to anchors: start and end, which, for the beginning , are set to some values and linked to each other:
Code:
start.num=0; strcpy(start.name,"START");
end.num=0; strcpy(end.name,"END"); //initialayzing start and end to zero.
Also , everything is managed by "current" pointer, which is set to point at start:
Code:
struct phone *current;
current=&start;
The function which add and links all the nodes together:
Code:
void link (struct phone *first){
struct phone *curr,*next; //curr will be the unit to be added, next is the original node after first
next=first->nxt;
curr=malloc(sizeof(struct phone));
get_name(curr);
get_phone(curr);
first->nxt=curr;
next->prv=curr;
curr->prv=first;
curr->nxt=next;
}
So far everything works! (you just have to pass current to link() )
The problem comes when I try to make a function which searches name by phone number.
The (originally) function went like this (start is passed down to find_name() ):
Code:
struct phone* find_name(struct phone anchor){
int fnum;
printf ("enter phone number to find:");
scanf("%d",&fnum);
struct phone *curr;
curr=&anchor; //we have no interest in start since it's not a real entrly
for(curr;curr->num!=fnum;curr=curr->nxt);
return curr;
}
It works only if the number is FOUND. If not – the program crashes.
I tried to modify the function in number of ways , all ways made the app crash, even if the number is there. Here what I've tried:
Code:
struct phone* find_name(struct phone anchor){
int fnum;
printf ("enter phone number to find:");
scanf("%d",&fnum);
struct phone *curr;
curr=&anchor; //we have no interest in start since it's not a real entrly
for(curr;(curr->num!=fnum)||(curr->num);curr=curr->nxt); //if curr=end, then curr->num=0 which will stop the loop
return curr;
}
Or
struct phone* find_name(struct phone anchor){
int fnum;
printf ("enter phone number to find:");
scanf("%d",&fnum);
struct phone *curr;
curr=&anchor; //we have no interest in start since it's not a real entrly
for(curr;(curr->num!=fnum)||(curr->num==0);curr=curr->nxt); //if curr=end, then curr->num=0 which will stop the loop
return curr;
and even
struct phone* find_name(struct phone anchor){
int fnum;
printf ("enter phone number to find:");
scanf("%d",&fnum);
struct phone *curr;
curr=&anchor; //we have no interest in start since it's not a real entrly
for(curr;(curr->num!=fnum)||strcmp(curr->name,"END");curr=curr->nxt);
return curr;
Yet, nothing seems to work. Help is needed please.
I can also upload the project as a zip file if more details are needed.
Sorry for the long post!