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?
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.
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.
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.
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.
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.
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