Pointer to Function in C

Previous
Next

Pointer to function:

  • It is also possible to create pointers to Derived data types such as function, array, string…..
  • To execute block of instructions, OS allocates the memory in stack area is called “FRAME”.
  • Every “FRAME” has a base address that is working like entry point to execute function.
  • Pointer to function variable holds a reference of FRAME.

Syntax:

            <return_type> (*<ptr_name>)(args_list);

Example:            

int (*fptr)(int,int);

  • In the above declaration “fptr” is a pointer can points to any function which is taking two integer arguments and returns integer-data.
  • Function-pointer declaration completely depends on prototype of function.
  • Prototype of function for above pointer variable :

            <return_type> <fun_name>(<args_list>)

#include<stdio.h>
int add(int,int);
int sub(int,int);
void main()
{
	int r1, r2, r3, r4;
	int (*fptr)(int,int);
	r1=add(10,20);
	r2=sub(10,20);
	printf("r1 : %d\nr2 : %d\n",r1,r2);
	
	fptr = &add; /*pointing to add function*/
	r3=fptr(30,50);

	fptr = &sub; /*pointing to sub function*/
	r4=fptr(30,50);
	printf("r3 : %d\nr4 : %d\n",r3,r4);
}
int add(int x, int y)
{
	return x+y;
}
int sub(int x, int y)
{
	return x-y;
}

Question: Why we need to place “fptr” inside parenthesis.

Answer: int (*fptr)(int,int);

Re-write as..

int  *fptr(int,int);

Will be considered as..

            int* fptr(int, int);

Note: The above declaration describes “fptr” is a function which is taking two integer arguments and returning “address of integer data”.

A function returning address:

            A function can return address of aggregate data type variable or user defined data type variable to access the data.

#include<stdio.h>
int* add(int,int);
void main()
{
	int a,b;
	int* c;
	printf("enter two numbers : ");
	scanf("%d%d",&a,&b);
	c = add(a,b);
	printf("sum : %d\n",*c);
}
int* add(int x, int y)
{
	int z;
	z=x+y;
	return &z;
}
Previous
Next

Add Comment

Courses Enquiry Form