Cata Cata
Cata Cata

Reputation: 111

C linked list gets modified when passed by pointer

I am trying to figure out why is my linked list modfied in the following program structure:

void edit(NODE pHead)
{
    /* Why is this modifying my list ?? */
    pHead->data = 1337;
}

void call(NODE *pHead)
{
    NODE pFirst = *pHead;

    for(int i = 0; i < 3; i++)
    {
        edit(*pHead);
        *pHead = (*pHead)->next;
    }

    *pHead = pFirst;
    printList(*pHead);
}

int main(int argc, char const *argv[])
{
    /* A simple list */
    NODE pList = NULL;

    /* The number of nodes */
    int n;
    scanf("%d", &n);

    /* Init list */
    for (int i = 0; i < n; i++)
    {
        //Read values.
        int timestamp;
        float data;
        scanf("%d%f", &timestamp, &data);

        //Add node.
        addLastNode(&pList, timestamp, data);
    }

    printList(pList);

    call(&pList);

    return 0;
}

I simply don't understand this. Isn't the edit function supposed to create a local copy of my linked list? When printing my final list, the output is the modified list, instead of the original one.Can someone explain to me what is wrong? Also here is my list structure:

/* A structure representing the node of a list */
typedef struct LIST
{
    int timestamp;
    float data;
    struct LIST *next;
} * NODE;

Upvotes: 0

Views: 154

Answers (1)

bruno
bruno

Reputation: 32596

Isn't the edit function supposed to create a local copy of my linked list?

having

void edit(NODE pHead)
{
     /* Why is this modifying my list ?? */
     pHead->data = 1337;
 }

and

typedef struct LIST
{
    int timestamp;
    float data;
    struct LIST *next;
 } * NODE;

NODE is pointer to a LIST, so in edit the cell is not a copy, and when you modify it the modification is not only local

It is exactly like that :

void edit(struct LIST * pHead)
{
     /* Why is this modifying my list ?? */
     pHead->data = 1337;
 }

this is the difference with :

 void edit(struct LIST pHead)
 {
     pHead.data = 1337;
 }

where the cell is local and the modification has no impact outside

This is why never use a typedef to hide a pointer because that let you supposing you manipulate a value while you manipulate a pointer

Upvotes: 1

Related Questions