Pass Pointers to Functions in C

Pass pointers to functions in C; In this tutorial, i am going to show you how to pass pointers as arguments to functions in c programming language with examples.

Pass Pointers to Functions in C

In C programming, Pointer as a function parameter is used to stores addresses of arguments in memory, passed during the function call. This is also known as call by reference. When a function is called by reference any change made to the reference variable will affect the original variable.

Note that – In C programming, it is also possible to pass the address of a variable to the function instead of the variable value.

It is possible to declare a pointer pointing to a function as an argument; will be declared as follows:

type (*pointer-name)(parameter);

Similarly, If a function wants to accept an address of two integer variable then the function declaration will be,

return_type function_name(int*,int*);

Here is an example :

int (*sum)();   //legal declaration of pointer to function
int *sum();     //This is not a declaration of pointer to function

A function pointer can point to a specific function when it is assigned the name of that function.

int sum(int, int);
int (*s)(int, int);
s = sum;

Here s is a pointer to a function sum. Now sum can be called using function pointer s along with providing the required argument values.

s (10, 20);

Example 1 – C Program To Swap Two Numbers using Pointers

#include <stdio.h>
void swap(int *n1, int *n2);
int main()
{
    int num1 = 15, num2 = 20;
    // address of num1 and num2 is passed
    swap( &num1, &num2);
    printf("num1 = %d\n", num1);
    printf("num2 = %d", num2);
    return 0;
}
void swap(int* n1, int* n2)
{
    int temp;
    temp = *n1;
    *n1 = *n2;
    *n2 = temp;
}

The output of the above c program will be:

num1 = 20
num2 = 15

Explanation of the above c program; as follows:

  • Passing the address of num1 and num2 variables into swap() function using this swap(&num1, &num2);
  • Pointers n1 and n2 accept these arguments in the function definition.
    • void swap(int* n1, int* n2) {
    • … ..
    • }
  • When *n1 and *n2 are changed inside the swap() function, num1 and num2 inside the main() function are also changed.
  • Inside the swap() function, *n1 and *n2 swapped. Hence, num1 and num2 are also swapped.
  • Notice that swap() is not returning anything; its return type is void.

Example 2 – Passing Pointers to Functions

#include <stdio.h>
int sum(int x, int y)
{
    return x+y;
}
int main( )
{
    int (*fp)(int, int);
    fp = sum;
    int s = fp(10, 15);
    printf("Sum is %d", s);
    return 0;
}

The output of the above c program will be:

25

More C Programming Tutorials

Leave a Comment