3

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?

melpomene
  • 84,125
  • 8
  • 85
  • 148
andy
  • 115
  • 2
  • 6

6 Answers6

6

You would need to use a pointer to a pointer:

foo(struct node **n) 

To change what n points to, you do:

*n = t;
Brian Roach
  • 76,169
  • 12
  • 136
  • 161
5

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).

Robert S. Barnes
  • 39,711
  • 30
  • 131
  • 179
  • 1
    `a copy of the value of the pointer` - I do understand that but not completely. We pass in a pointer, why can't we change it? It's a pointer after all. – Incerteza Sep 07 '14 at 19:41
  • Maybe this other post will clarify the matter for you: http://stackoverflow.com/questions/21604946/pointer-to-pointer-clarification/21605097#21605097 – Robert S. Barnes Sep 08 '14 at 06:21
4

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.

Šimon Tóth
  • 35,456
  • 20
  • 106
  • 151
4

No, you cannot change any argument passed by value.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
  • 1
    The function receives a copy of the pointer; therefore, the pointer itself was passed by value. Of course, what the pointer points to is, in effect, being passed by reference. – Jonathan Wood Sep 07 '14 at 20:09
  • Note that you *can* pass a pointer by reference. But this is done by passing the address of the pointer. In that case, you are actually passing a pointer to a pointer. But you are still passing *some* pointer, and the pointer you pass will always be passed by value. – Jonathan Wood Sep 07 '14 at 20:31
1

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.

Erik
  • 88,732
  • 13
  • 198
  • 189
0

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 */
}
pmg
  • 106,608
  • 13
  • 126
  • 198