Facebook Page Twitter Page LinkedIn Page
× C++ Q&A


In C++, a function can accept pointer as argument and when a pointer is passed as argument(s) in the function, then the function takes the address of the parameter(s) and any operation(s) performed on the passed parameter(s) is performed at its memory location inside the function. This means that any changes made to the parameter(s) inside the function will change the parameter(s) itself also.

Example:

In the below example, the function called Square is created which takes argument as pointer and returns square of the passed argument. The function takes the address of the parameter and modify the parameter as square of itself at its memory location. In the main() function, when the passed argument is printed after calling the function Square, the value of the parameter get changed because it was changed at its memory location.

#include <iostream>
using namespace std;
int Square(int *x); 

int main (){
    int x = 5;
    cout<<Square(&x)<<"\n"; 
    cout<<x<<"\n";
    return 0;
}

int Square(int *x){
    *x = (*x)*(*x);
    return *x; 
}

The output of the above code will be:

25
25

In C++, a function accepts pointer as an argument and can take array as well as shown in the below example.

#include <iostream>
using namespace std;
int ArrayAverage(int *arr, int n); 

int main (){
    int n = 5;
    int arr[n] = {10, 20, 30, 40, 50};
    int *p = arr;
    cout<<ArrayAverage(p, n)<<"\n"; 
    return 0;
}

int ArrayAverage(int *arr, int n){
    int sum = 0;
    for(int i = 0; i<n; i++)
    {
       sum = sum + arr[i];
    }
    return sum/n; 
}

The output of the above code will be:

30