Passing Pointers to Functions In C++
Last Updated :
28 Nov, 2022
Prerequisites:
Passing Pointers to functions means declaring the function parameter as a pointer, at the function calling passing the address of the variable and that address will be stored by a parameter that is declared as a pointer.
To change the value of any variable in the function we have to pass the address of that variable in the function.
Example:
C++
#include <iostream>
using namespace std;
void fun( int x) { x = 5; }
int main()
{
int x = 9;
cout << "value of x before calling fun: " << x << endl;
fun(x);
cout << "value of x after calling fun: " << x << endl;
return 0;
}
|
Output
value of x before calling fun: 9
value of x after calling fun: 9
In the above code, the address of the value of the element x does not get affected by the value change in the function as the address of both the variables are different.
Another case can be where we want to change its value in the function. In such cases we use pointers.
Example:
C++
#include <iostream>
using namespace std;
void fun( int * ptr) { *ptr = 5; }
int main()
{
int x = 9;
cout << "value of x before calling fun: " << x << endl;
fun(&x);
cout << "value of x after calling fun: " << x << endl;
return 0;
}
|
Output
value of x before calling fun: 9
value of x after calling fun: 5
In the above code, the actual value of x is passed as we are passing the address which is stored by a pointer ptr.
Example:
C++
#include <iostream>
using namespace std;
void swap( int x, int y)
{
int temp = x;
x = y;
y = temp;
}
int main()
{
int a = 2, b = 5;
cout << "values of a and b before swapping: " << a
<< " " << b << endl;
swap(a, b);
cout << "values of a and b after swapping: " << a << " "
<< b << endl;
return 0;
}
|
Output
values of a and b before swapping: 2 5
values of a and b after swapping: 2 5
Example:
C++
#include <iostream>
using namespace std;
void swap( int * x, int * y)
{
int temp = *x;
*x = *y;
*y = temp;
}
int main()
{
int a = 2, b = 5;
cout << "values of a and b before swapping: " << a
<< " " << b << endl;
swap(&a, &b);
cout << "values of a and b after swapping: " << a << " "
<< b << endl;
return 0;
}
|
Output
values of a and b before swapping: 2 5
values of a and b after swapping: 5 2
Function Pointer on Array
An array is a type of Data structure with continuous memory blocks which can store data with a similar data type. Also, the name of the array represents its first memory block address. So, we can use this property to access the elements of the array.
To know more about it, refer to the article – Array in C++.
Example:
C++
#include <iostream>
using namespace std;
void display( int * ptr, int n)
{
for ( int i = 0; i < n; ++i) {
cout << *(ptr + i) << " " ;
}
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
int n = sizeof (arr) / sizeof ( int );
int * ptr = arr;
display(ptr, n);
return 0;
}
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...