0

I have been writing a doubly linked list in C, and even though the function for inserting an element to the back of the list seems correct to me, the element is not added. Debugging showed that the values are assigned to the corresponding Pacijent instances, however, the front and back of the list are still NULL.

Here's the code:

struct Pacijent
{
    char ime[10];
    [...]
    Pacijent *prev;
    Pacijent *next;
};

Pacijent noviPacijent(char i[], char p[], char io[], int jmb[], double v, double t, int s)
{
    Pacijent *novi = (Pacijent*)malloc(sizeof(Pacijent));
    memcpy(novi->ime, i, strlen(i)+1);
    [...]
    return *novi;
}

struct Lista
{
    Pacijent *front;
    Pacijent *back;
};

void assign(Pacijent p1, Pacijent p2)
{
    memcpy(p1.ime, p2.ime, strlen(p1.ime)+1);
    [...]
}

void insertBack(Pacijent p, Lista l)
{
    Pacijent *novi = (Pacijent*)malloc(sizeof(Pacijent));
    assign(*novi, p);
    if (l.back == NULL)
    {
        l.front = l.back = novi;
        novi->prev = NULL;
        novi->next = NULL;
    }
    else
    {
        novi->prev = l.back;
        l.back->next = novi;
        novi->next = NULL;
        l.back = novi;
    }
}

int main()
{
    Lista *lista = (Lista*)malloc(sizeof(Lista));
    lista->back = lista->front = NULL;

    int jmb2[13] = { 1, 2, 0, 1, 9, 9, 3, 0, 0, 0, 0, 0, 0 };
    [...]
    Pacijent p2 = noviPacijent("Mladen", "Markovic", "Milan", jmb2, 1.85, 75, 21);

    insertBack(p2, *lista);
}

1 Answer 1

3

Look at:

void insertBack(Pacijent p, Lista l)

This function takes a Lista value as argument, not a Lista pointer. This means that if you change anything about l, it will not have an effect outside of the function. When you call insertBack, you are actually copying your list, and then you add an element to the temporary list.

Edit: The same is happening with your assign function, the changes you make to p1 won't have any effect outside of the function because you pass it as a value and not as a pointer.

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

Comments

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.