Passing a pointer to a functionThis tip submitted by Irfaan Kamo on 2012-05-20 18:27:57. It has been viewed 20628 times.
Rating of 6.0 with 104 votes
void function(int* p)
//Changing the address to where p points.
int* number = new int(5);
p = number;
int* pointer = new int(1);
cout << *pointer;
When we run the program it will print out 1. This is because the function creates a local copy of the pointer, so whatever it does within the function doesnt affect the real pointer.
In order to get around this we can pass the pointer by reference:
void function(int* &p)
This will ensure that we work with the actual pointer being passed and not just a copy of it.
(Note that its always a good idea to delete the pointer before reassigning it to another address since not doing so will result in memory leaks.)
Help your fellow programmers! Add a tip!