user3092118
user3092118

Reputation: 371

Proper way to modify a linked list item in C

I am working with linked lists in C and trying to understand the correct way of passing a node to a function and modifying that node's value.

Assume for the sake of these examples that I have a single-node list and only care about modifying that first node.

struct node {
    int value;
    struct node *next
};

In main I declare my (single node) list:

int main(){ 
    struct node *first;
    first = malloc(sizeof(struct node));
    first->value = 5;
    first->next  = NULL;
    //someFunctA(first);
    //someFunctB(&first);
};

To modify first->value in a function, should I use:

void someFunctA(struct node *modify){
    modify->value = 10;}

or:

void someFunctB(struct node **modify){
    struct node *temp = *modify;
    temp->value = 10;}

(Or neither of these?)

Both of seem to work - after calling either someFunctA(home) or someFunctB(&home) and I see the expected value in first->value in main() after calling them (10 in this case).

Are either of these methods correct? Both? If both, what are the tradeoffs between the two?

Also, is it possible to pass first with a reference pointer (as in someFunctB, right?) and still work on it directly without making a copy? (When I pass with the reference pointer and attempt to access modify->value, *modify->value or **modify->value in the function, I get the error request for member ‘value’ in something not a structure or union.)

Upvotes: 1

Views: 5423

Answers (1)

Andy Schweig
Andy Schweig

Reputation: 6749

Yes, both of those will work, but you probably want the first version. You're passing a pointer to the node so your function is able to modify the node itself. The second version gives you the ability to modify the pointer (i.e., the variable first in main()), but if you don't need to do that, there's no reason to use the second option.

As to your question about using modifydirectly in the second function, the correct syntax is (*modify)->value = 10.

Upvotes: 2

Related Questions