So I have created two structures LIST (consists of head and last pointer) and NODE (consists of next and previous pointer). I have a function create_list (LIST *p) that does the following:
Sets the head and last pointer to NULL
Asks the user to enter the no of nodes for the list and also lets user enter the value and it inserts a node in an orderly manner (increasing order)
Once done, it displays the list
So I created two LIST pointer variables and tried making two doubly linked list, it works perfectly for the first list but the second list does not get initialized.
Here is the code:
void create_list(LIST *p){
int x;
printf("enter no of elements to enter\n");
scanf("%d", &x);
printf("creating a list of size %d\n", x);
p->head =NULL;
p->last=NULL;
printf("initialised list\n");
for(int i =0; i<x; i ){
ins(p);
}
display(p);
}
int main(){
LIST* list1, *list2;
create_list(list1);
create_list(list2);
return 0;
}
CodePudding user response:
LIST* list1, *list2;
isn't doing what you think its doing. These pointers are pointing at a random location in memory. They need to point at a LIST
type somewhere. In other words, there is no LIST in existence in your code. This is undefined behavior, so the fact that the first one initialized correctly was only by chance.
For example, if I wanted them to exist in main
's stack:
LIST list1, list2;
create_list(&list1);
create_list(&list2);
Now 2 LIST
s exist, and we have passed their addresses to create_list
.