Reputation: 158
I cannot print the entire linked list.. what's my mistake? I'm new to linked list..
This is the base structure
struct data {
int id;
int age;
struct data *next;
};
main function
int main() {
int mode;
struct data *initial;
struct data *insert;
struct data *temp;
insert = initial;
printf("1. Insert\n5. Print List\n");
while (1) {
printf("Mode: ");
scanf("%d", &mode);
if (mode == 1) {
insert = malloc(sizeof(struct data));
printf("Id: ");
scanf("%d", &(insert->id));
printf("Age: ");
scanf("%d", &(insert->age));
insert=insert->next;
} else if (mode == 5) {
temp = initial;
while (temp != insert) {
printf("Id: %d\tAge: %d\n", temp->id, temp->age);
temp = temp->next;
}
}
}
}
thank you for your help.
Upvotes: 1
Views: 126
Reputation: 206567
In addition to the points made by @JonathanLeffler, I see problems in this block of code:
if(mode==1)
{
insert=malloc(sizeof(struct data));
printf("Id: ");scanf("%d",&(insert->id));
printf("Age: ");scanf("%d",&(insert->age));
insert=insert->next;
}
First time you execute this block, you do the following:
struct data
and let insert
point to it.struct data
.insert
become insert->next
. But insert->next
was not initialized to anything before the statement. At the end of the statement insert
points to something completely unpredictable.Second time you execute this block, you do the following:
struct data
and let insert
point to it.struct data
.insert
become insert->next
. But insert->next
was not initialized to anything before the statement. At the end of the statement insert
points to something completely unpredictable.What happened here?
malloc
.insert
still points to something unpredictable.This process repeats every time you execute that loop.
Here's what you can to to fix it.
if(mode==1)
{
// Allocate memory and let temp point
// to the allocated memory.
temp=malloc(sizeof(struct data));
// Fill up the data of the newly allocated memory.
printf("Id: ");scanf("%d",&(temp->id));
printf("Age: ");scanf("%d",&(temp->age));
// Make temp clean by making its next point to NULL.
temp->next = NULL;
// Now figure out where to link this newly allocated
// memory to the linked list.
// Assuming you initialize insert correctly...
if ( insert == NULL )
{
initial = insert = temp;
}
else
{
insert->next = temp;
insert = temp;
}
}
Hope that makes sense.
Upvotes: 1
Reputation: 753525
You never initialize initial
to anything, not even NULL
or 0
, so there's no way you can chase a list from it sensibly.
You also need to set insert->next = NULL;
after the two scanf()
calls and before the assignment insert = insert->next;
. You need to hook insert
into the original list somehow; maybe with struct data *initial = 0;
when it is declared and if (initial == 0) initial = insert;
before the insert = insert->next;
.
You also need to do more error checking: scanf()
and malloc()
can both fail, and you should do something sensible when they do.
Upvotes: 2