0 votes
44 views
asked in C++ by
Hi

   C++ How to Passing a pointer to a function?

1 Answer

0 votes
answered by

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

Categories

...