andy
andy

Reputation: 115

change pointer passed by value

I have given a function foo(struct node *n) where n is the head node in a linked list. Now foo should change n s.t. it points to the end of the list.

But is this possible with this function signature?

Assuming t is the pointer to the end of the list:

Did I miss something?

Upvotes: 3

Views: 6313

Answers (6)

Jonathan Wood
Jonathan Wood

Reputation: 67251

No, you cannot change any argument passed by value.

Upvotes: 4

Šimon Tóth
Šimon Tóth

Reputation: 36441

You didn't miss anything. It's not possible with the given function declaration.

As you wrote, the pointer is passed by value, therefore if changed, it won't propagate to the original variable.

You need to change the prototype to foo(struct node **n); or struct node *foo(struct node *n); and return the new pointer as result.

Upvotes: 4

Robert S. Barnes
Robert S. Barnes

Reputation: 40568

No, because you have a copy of the value of the pointer that's been passed in. You have no access to the original pointer that was passed in. In order to modify the pointer outside the function the sig would need to be foo( struct node **n).

Upvotes: 5

Erik
Erik

Reputation: 91300

You can't change n and have the caller see the change. You can change n->prev->next and n->next->prev though - that may be what you need.

Upvotes: 1

pmg
pmg

Reputation: 108978

It is impossible for the change to be reflected in the calling function. However, inside foo, you can change n to your heart's content.

int foo(struct node *n) {
    n = NULL; /* ok */
}

Upvotes: 0

Brian Roach
Brian Roach

Reputation: 76908

You would need to use a pointer to a pointer:

foo(struct node **n) 

To change what n points to, you do:

*n = t;

Upvotes: 6

Related Questions