pass by reference and value with pointers

TheFuzz picture TheFuzz · Jan 23, 2011 · Viewed 19.9k times · Source

I don't understand why passing a pointer to a function doesn't change the data being passed in. If the function proto looked like this:

void func( int *p ); 

and func allocated memory to p, why can't it be used outside of the function? I thought that pointers were addresses?

Answer

Oliver Charlesworth picture Oliver Charlesworth · Jan 23, 2011

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.