In this tutorial, you will learn how to pass a pointer to a function as an argument. To understand this concept you must have a basic idea of Pointers and functions in C programming.
Just like any other argument, pointers can also be passed to a function as an argument. Lets take an example to understand how this is done.
Example: Passing Pointer to a Function in C Programming
In this example, we are passing a pointer to a function. When we pass a pointer as an argument instead of a variable then the address of the variable is passed instead of the value. So any change made by the function using the pointer is permanently made at the address of passed variable. This technique is known as call by reference in C.
Try this same program without pointer, you would find that the bonus amount will not reflect in the salary, this is because the change made by the function would be done to the local variables of the function. When we use pointers, the value is changed at the address of variable
#include <stdio.h> void salaryhike(int *var, int b) { *var = *var+b; } int main() { int salary=0, bonus=0; printf("Enter the employee current salary:"); scanf("%d", &salary); printf("Enter bonus:"); scanf("%d", &bonus); salaryhike(&salary, bonus); printf("Final salary: %d", salary); return 0; }
Output:
Enter the employee current salary:10000 Enter bonus:2000 Final salary: 12000
Example 2: Swapping two numbers using Pointers
This is one of the most popular example that shows how to swap numbers using call by reference.
Try this program without pointers, you would see that the numbers are not swapped. The reason is same that we have seen above in the first example.
#include <stdio.h> void swapnum(int *num1, int *num2) { int tempnum; tempnum = *num1; *num1 = *num2; *num2 = tempnum; } int main( ) { int v1 = 11, v2 = 77 ; printf("Before swapping:"); printf("\nValue of v1 is: %d", v1); printf("\nValue of v2 is: %d", v2); /*calling swap function*/ swapnum( &v1, &v2 ); printf("\nAfter swapping:"); printf("\nValue of v1 is: %d", v1); printf("\nValue of v2 is: %d", v2); }
Output:
Before swapping: Value of v1 is: 11 Value of v2 is: 77 After swapping: Value of v1 is: 77 Value of v2 is: 11
Raymond says
Good Day Author, I Like your article; it has been very helpful. Please… Can you send me a PDF copy so I can reference it any time I need it?
thanks