Reputation: 494
I'm trying to implement a linked list in c. I get input from user, put it in a struct called Box, and save the order of the inputs using a linked list. here is the struct :
struct Box
{
struct Box *previous;
struct Box *next;
int amount;
};
and here is the implementation :
void main()
{
struct Box firstBox;
scanf("%d", &(firstBox.amount));
struct Box *addressKeeper;
addressKeeper = &firstBox;
for (int i = 0; i < 3; i++)
{
struct Box newBox;
scanf("%d", &(newBox.amount));
newBox.previous = addressKeeper;
addressKeeper->next = &newBox;
addressKeeper = &newBox;
}
}
but when I print the next
boxes' addresses in this way, all of them are the same?
struct Box *ptr = &firstBox;
for (int i = 0; i < 3; i++)
{
printf("%p \n", ptr->next);
ptr = ptr->next;
}
am I doing something wrong?
Upvotes: 0
Views: 70
Reputation: 562
You are not creating the new Box elements correctly in the loop. You have one struct Box that goes out of scope every pass through the loop. You would need to allocate each one dynamically via malloc() or else allocate an array that you draw from. Something like this:
struct Box listOfBoxes[3];
struct Box *addressKeeper;
addressKeeper = &listOfBoxes[0];
for (int i = 1; i < 3; i++)
{
scanf("%d", &(listOfBoxes[i].amount));
listOfBoxes[i].previous = addressKeeper;
addressKeeper->next = &listOfBoxes[i];
addressKeeper = &listOfBoxes[i];
}
However, you need to examine the next and previous pointer assignments carefully. There is still something wrong there that I didn't change.
Upvotes: 0
Reputation: 310930
You are using local object newBox
in this loop
for (int i = 0; i < 3; i++)
{
struct Box newBox;
scanf("%d", &(newBox.amount));
newBox.previous = addressKeeper;
addressKeeper->next = &newBox;
addressKeeper = &newBox;
}
After the loop accessing this object invokes undefined behavior because it is not alive anymore.
It seems your program outputs the same address of this local object.
Either you need to allocate dynamically nodes or use an array of nodes declared before the loop.
Upvotes: 1