Reputation: 115
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:
n = t
won't work because the pointer is passed by value.*n = *t
won't work because I would overwrite the head of the list.Did I miss something?
Upvotes: 3
Views: 6313
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
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
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
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
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