0

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?

2
  • You set ptr equal to the address of the first box, but you never advance it inside the for loop, so you print the same value multiple times. You need to do something like ptr = ptr->next; inside the loop. Commented Nov 5, 2020 at 21:12
  • I'm sorry it was a mistake in the copy paste. I edited this. the problem still exists Commented Nov 5, 2020 at 21:13

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Thank you very much for your help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.