The other answers are good advice. But also, if you have control over the bar
function, and need to be able to change in bar
to what object your mystruct *
pointer points to (which is probably the reason why you have a double pointer in the first place), then the cleanest approach is to use the following signature for bar
:
void bar(unsigned int val, mystruct * &foo);
It passes by reference a pointer, so you are able to change to what object the pointer points to, without sacrificing readability of the code, for instance:
int main()
{
mystruct * foo = new mystruct;
bar(42, foo);
}
void bar(unsigned int val, mystruct * &foo)
{
foo->member1 = val;
foo = new mystruct;
}
A complete usage scenario without memory leak could be:
int main()
{
// allocate dynamically a mystruct whose member1 is equal to 1.
mystruct * foo1 = new mystruct;
mystruct * foo2 = foo1;
foo1->member1 = 1;
// pass by reference foo1
bar(42, foo1);
// here, foo1->member1 == 42 and foo2->member1 == 10
// free memory
delete foo1; // the one allocated in bar()
delete foo2; // the one allocated in main()
}
void bar(unsigned int val, mystruct * &foo)
{
// modify the object allocated in main()
foo->member1 = 10;
// allocate dynamically a mystruct, store its address in foo
foo = new mystruct;
foo->member1 = val;
}