0

I used a function to insert new nodes to my singly-linked list but when i print out all the values inside the nodes after insertion, i only get the value of the first node:

// Make list
createList(head, 17);

// Insert to list
for (int x = 9; x > 0; x /= 3)
{
    if (!insertToList(head, x))
    {
        fprintf(stderr, "%s", error);
        return 1;
    }
}

The function:

bool insertToList(NODE *head, int value)
{
    NODE *node = malloc(sizeof(NODE));
    if (node == NULL)
        return false;

    node -> number = value;
    node -> next = head;
    head = node;
    return true;
}

-- Output: 17

When i don't use a function, everything works as expected:

// Make list
createList(head, 17);

// Insert to list
for (int x = 9; x > 0; x /= 3)
{
    NODE *node = malloc(sizeof(NODE));
    if (node == NULL)
    {
        fprintf(stderr, "%s", error);
        return 1;
    }

    node -> number = x;
    node -> next = head;
    head = node;
}

-- Output: 1 3 9 17

Why ?

1
  • 1
    That's because you have modified only a copy of the head pointer. Commented Oct 28, 2017 at 20:17

1 Answer 1

1

You are passing the pointer in the function, updating it and not returning it back in which case, the outside function can never know if the head has changed. You must update the head appropriately in the for loop as well.

In the case where you don't use the function, your for loop knows the correct address ofhead every time you insert.

Probably if you return the head pointer and properly update that, it should solve your problem.

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

1 Comment

Thank you very much, your solution solved my problem.

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.