pass by reference and value with pointers [duplicate]

Whilst something like this does what you expect:

void func(int *p)
{
    *p = 1;
}

int a = 2;
func(&a);
// a is now 1

this does not

void func(int *p)
{
    p = new int;
}

int *p = NULL;
func(p);
// p is still NULL

In both cases, the function works with a copy of the original pointer. The difference is that in the first example, you’re trying to manipulate the underlying integer, which works because you have its address. In the second example, you’re manipulating the pointer directly, and these changes only apply to the copy.

There are various solutions to this; it depends on what you want to do.

Leave a Comment