C

Example Of Passing A Pointer To A Function In C

In this tutorial, you will learn how to pass a pointer as an argument to a function. To grasp this concept, you must be familiar with pointers and functions in C programming.
Pointers, like any other argument, can be passed to a function as an argument. Let’s look at an example to see how this is done.

In C programming, an example is passing a pointer to a function.

In this example, we’re passing a function pointer. When we pass a pointer as an argument rather than a variable, the address of the variable is passed rather than the value. As a result, any change made by the function using the pointer is made permanently at the address of the passed variable. In C, this is known as call by reference.
If you run the same program without the pointer, you will notice that the bonus amount does not appear in the salary. This is because the function changes the local variables of the function. When we use pointers, the value of the variable is changed at the address of the 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: Using Pointers to swap two numbers

This is one of the most common examples of using call by reference to swap numbers.
If you run this program without any pointers, you will notice that the numbers are not swapped. The reason is the same as we saw 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

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button