Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I modify the target of a pointer passed as parameter?

Can a function change the target of a pointer passed as parameter so that the effect remains outside the function?

void load(type *parameter)
{
    delete parameter;
    parameter = new type("second");
}

type *pointer = new type("first");
load(pointer);

In this minimal example, will pointer point to the second allocate object? If not, how can I get this kind of behavior?

Update: To clarify my intention, here is the code I would use if the parameter would be a normal type instead of a pointer. In this case I would simply use references.

void load(type &parameter)
{
    parameter = type("second");
}

type variable("first");
load(&variable);

That's easy but I try to do the same thing with pointers.

like image 621
danijar Avatar asked Dec 17 '25 19:12

danijar


2 Answers

No.

parameter will get a copy of the value of pointer in this case. So it is a new variable. Any change you make to it is only visible with in the function scope. pointer stays unmodified.

You have to pass the pointer by reference

void load(type *& parameter)
                ^
{
like image 126
stardust Avatar answered Dec 20 '25 09:12

stardust


You need to pass the pointer by reference:

void load(type *&parameter);

See for example http://www.cprogramming.com/tutorial/references.html

like image 21
NonNumeric Avatar answered Dec 20 '25 11:12

NonNumeric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!