Passing Pointer to Function in C++

C++ programming language allows us to pass pointer to a function as argument. We can pass the address of the variable to the formal arguments of a function. This way of calling a function by passing pointer arguments is known as call by reference.

Any change in the value of formal parameters inside function's body will affect the value of actual parameter because both are pointing to same memory location.

To pass a pointer to a function, we have to declare the function argument of pointer type.


Different ways of declaring function which takes an array as input

Function argument as a pointer to the data type of array.
int testFunction(int *array){
 // Function body
}
By specifying size of an array in function parameters.
int testFunction(int array[10]){
// Function body
}
By passing unsized array in function parameters.
int testFunction(int array[]){
// Function body 
}

C++ program to pass pointer to a function

#include <iostream>
using namespace std;
   
void getDoubleValue(int *ptr){
   *ptr = (*ptr) * 2;
   cout << "F(Formal Parameter) = " << *ptr << endl;
}
  
int main(){
   int A;
   cout << "Enter a number\n";
   cin >> A;
   // Calling function by passing address of A
   getDoubleValue(&A);
   /* Any change in the value of formal parameter(F)
   will effect the value of actual parameter(A) */
   cout << "A(Actual Parameter) = " << A;
   
   return 0;
}

Output
Enter a number
23
F(Formal Parameter) = 46
A(Actual Parameter) = 46

Not only single variables, we can pass pointer to a array, structures, objects and user defined data types also. Here is an example of passing an array to a function in C++.


C++ program to pass an array to a function

#include <iostream>
using namespace std;
 
// This function takes integer pointer as argument
void printArrayOne(int *array, int size){
    int i;
    for(i=0; i<size; i++){
        cout << array[i] << " ";
    }
    cout << endl;
}
 
int main(){
   int score[5]={1, 2, 3, 4, 5};
   // Passing name of array 
   printArrayOne(score, 5);
    
   return 0;
}

Output
1 2 3 4 5