C++ - Passing Pointer to Function
In C++, a function can accept pointer as argument and when a pointer is passed as argument in the function, then the function takes the address of that parameter and any operation performed on the passed parameter is performed at its memory location inside the function. This means that any changes made to the parameter inside the function will change the parameter itself also.
Example:
In the example below, the function called Square is created which takes a argument as pointer and returns the square of it. It takes the address of the parameter and modify the parameter to the square of itself at its memory location. Therefore, when the passed argument is printed after calling the function, its value gets changed.
#include <iostream> using namespace std; int Square(int *x){ *x = (*x)*(*x); return *x; } int main (){ int x = 5; cout<<"Value of x: "<<x<<"\n"; cout<<"Function returns: "<<Square(&x)<<"\n"; cout<<"Value of x: "<<x<<"\n"; return 0; }
The output of the above code will be:
Value of x: 5 Function returns: 25 Value of x: 25
A function which accepts pointer as an argument and can also accept an array. Consider the example below:
#include <iostream> using namespace std; int ArrayAverage(int *arr, int n); int main (){ int n = 5; int Arr[n] = {10, 20, 30, 40, 50}; cout<<"Average of all elements of Arr = "<< ArrayAverage(Arr, 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:
Average of all elements of Arr = 30
❮ C++ - Pointers