Passing pointer to function

In the C programming language there is also a provision to pass a pointer to the functions as an argument other than variables.

Example:

#include <stdio.h>

void fun (int * ptr)
{
  *ptr =11;
}

int main ()
{
   int a = 10;
   int *ptr = &a;
   printf ("\n The value before passing pointer is: %d\n", *ptr);
   fun (ptr);
   printf ("\n The value after passing pointer is: %d\n", *ptr);
   return 0;
}

Output:

The value before passing pointer is: 10

The value after passing pointer is: 11

Since the address is passed(pass-by-reference), the value modified in the called function is also reflected in the caller function.

Passing address to a function:

The below programs swap the value of the two variables

#include <stdio.h>

void swap (int *num1, int *num2)
{
  int temp = *num1;
  *num1 = *num2;
  *num2= temp;
}

int main ()
{
  int num1 = 10;
  int num2 = 20;
  printf("\n Value before swap is num1: %d and num2 is: %d\n", num1, num2);  
  swap (&num1, &num2);
  printf("\n Value after swap is num1: %d and num2 is: %d\n", num1, num2);
  return 0;
}

Output:

 Value before swap is num1: 10 and num2 is: 20

 Value after swap is num1: 20 and num2 is: 10

Relevant Topics:



Categories: C Language

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: