WildDev
WildDev

Reputation: 2367

C++ pass linked list to the function and change it by different ways

I have to write a function that works with linked list not only with the copied instance but also with the original instance. Here is what I have tried:

/* Want to change the real instance */
void fun1 (MyList *list)
{
list = list->next; // working with local copy
*&list = *&list->next; // changes the real instance, but it doesn't work..Why?
}

/* Want to change AS local copy */
void fun2 (MyList *&list)
{
list = list->next; // changes the real instance, works fine.
// ..And there I want to make some changes AS with local copy..How?
}

I hope you understand what I mean. :) Any ideas?

Upvotes: 1

Views: 4740

Answers (2)

Jerry Coffin
Jerry Coffin

Reputation: 490108

*&list = *&list->next; // changes the real instance, but it doesn't work..Why?

It doesn't work because it's taking the address of the argument that was passed to the function (i.e., the local copy) then dereferencing that address to refer to the local copy.

Your second version (passing a reference to a pointer) makes getting a local copy easy:

auto local = list;

or:

MyList *local = list;

...will both work fine.

Upvotes: 0

UmNyobe
UmNyobe

Reputation: 22890

&list give you the address of the local variable, which is the position of the argument on the stack, and then you deference it again. So you are still working on the local copy.

You need to pass the address of the list, by changing to a signature to either

  void fun1 (MyList **plist);
  void fun1 (MyList *&plist);

to be able to modify the list itself.

Upvotes: 3

Related Questions