C Pointers and Functions

Pointer is used in function to hold address of  function parameter at the time of function call, also this is called call by reference. So if we perform any modification to that parameter will reflect to its formal argument.

An example of call by reference

#include<stdio.h>

/* address of num is received by a pointer variable */

void fun(int *x)

{

*x = 20;  /* Modifying value of num*/

}

int main()

{

int num = 10;

printf(“Initial value of num = %d\n”,num);

fun(&num);  /* Passing address of num as an argument */

printf(“Value of num after function call = %d\n”,num);

return 0;

}

Output:

Initial value of num = 10

Value of num after function call = 20

Function returning pointer

In function chapter we have learn about function return type, here we will see how function return pointer. See an example

Write a program which takes pointer to integer as an argument and return pointer to integer.

#include<stdio.h>

/* A proram to return greater of  two integer  */

int * fun(int *x, int *y)

{

if(*x > *y)

return *x;

else

return *y;

}

int main()

{

int num = 10;

int num1 = 20;

int *greater;

sum = fun(&num, &num1);  /* Passing address of num and num1 as an argument */

printf(“Greater = %d\n”,*greater);

return 0;

}

Output:

Greater = 30 

Function pointer or  Pointer to function

As we know pointer variable stores or holds memory address likewise also it can hold address of a function. A function pointer is a variable that stores or holds the address of a function that can be access through that pointer variable.

Syntax of function pointer

data_type  (*fun_name) (arg1, arg2,..);    Let’s  take an example below

int (*fun) (int x);

fun is a pointer to function that taking one argument of type int and that returns of type int.

int *fun ()  /* This is not a declaration of function pointer */

An example of function pointer

#include< stdio.h>

int sum(int x, int y)

{

 return x+y;

}

int main( )

{

 int (*fun_pointer)(int, int);

 fun_pointer = sum;

 int num, num1, total;

num = 10;

num1 = 20

/* Calling fun sum() through function pointer */

total = fun_pointer(num, num1);

 printf(“Sum = %d\n”,total);

return 0;

}

Output:

Sum = 30

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.