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 ¶meter)
{
parameter = type("second");
}
type variable("first");
load(&variable);
That's easy but I try to do the same thing with pointers.
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)
^
{
You need to pass the pointer by reference:
void load(type *¶meter);
See for example http://www.cprogramming.com/tutorial/references.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With