Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass by reference and value with pointers [duplicate]

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?

like image 275
TheFuzz Avatar asked Jan 23 '11 19:01

TheFuzz


People also ask

Are pointers passed by reference or value?

Pointers are passed by value as anything else. That means the contents of the pointer variable (the address of the object pointed to) is copied. That means that if you change the value of the pointer in the function body, that change will not be reflected in the external pointer that will still point to the old object.

Does passing by reference make a copy?

pass-by-reference does not make any copy, it gets the reference of the object itself by just renaming it, so no any copying operation.

Are pointers passed by reference in C?

There is no such thing as reference in C. Passing a pointer to a function will not copy the object that the pointer is pointing to.

Are pointers copied by value?

Now, when passing a pointer to a function, you are still passing it by value. Indeed, the value of the pointer variable is copied into the function. In the example above, this means that a copy of px , namely a copy of the address of x (e.g., 5678 ), is passed to the function.


1 Answers

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.

like image 197
Oliver Charlesworth Avatar answered Sep 24 '22 01:09

Oliver Charlesworth