Passing a pointer to a function

This tip submitted by Irfaan Kamo on 2012-05-20 18:27:57. It has been viewed 34385 times.
Rating of 5.5 with 192 votes



void function(int* p)
{
//Changing the address to where p points.
int* number = new int(5);
p = number;
}

int main()
{
int* pointer = new int(1);
funtion(pointer);
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.)



More tips

Help your fellow programmers! Add a tip!