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.
Arguments in C and C++ are passed by value. That means if type of the argument is a pointer to int
, then the function receives a copy of the actual pointer argument, while still being able to change the int
being pointed to.
It's really hard to say, what you're asking..
My guess - you can change the memory, that is pointed by the pointer p
, but you can't "redirect" or delete the pointer (or allocate memory )? If so, pass you pointer as reference:void func( int &*p )
Or as double pointervoid func( int **p )
to be able to change it (i'm talking about the pointer)
Pointers are addresses. If you pass a pointer into a function, the function can then modify data created outside the scope of the function. However, if you want to allocate memory inside a function for use outside the function, you need to pass in a double pointer. The reason is that pointers are passed by value, and the allocation assigns a new value to the pointer for the newly allocated block. But that new value is lost when the function returns. But you can use this method to do what you need:
void func(int * * pp)
{
* pp = new int;
}
use the func thus:
int * myPointer;
func(& myPointer);
// do stuff with myPointer
delete myPointer;
I wouldn't agree to Nikolai's answer. In C++ there are two ways of passing the arguments.
f(Type Name)
is your case, where Type is int*
and Name is p
(note that int *p
actually means int* p
). In this case, inside your function Name is a copy of the object that you pass to the function.
The second way
f(Type & Name)
does not make a copy, but creates an alias to the object instead, so that you can modify the original object.
In your case, the object is the pointer of a type int*
. As you pass it using the first syntax, you get a copy of it which you modify and the original pointer is left unchanged. If you want to change the original pointer, then you should pass it by reference, so for Type=int*
and Name=p
you'd get
f(int*& p)