Pointer to Function in C: Usage and Examples

Rumman Ansari   Software Engineer   2024-07-05 03:50:47   8204  Share
Subject Syllabus DetailsSubject Details 1 Questions 8 Program
☰ TContent
☰Fullscreen

Table of Content:

A function has a physical location in memory that can be assigned to a pointer. This address is the entry point of the function and it is the address used when the function is called. Once a pointer points to a function, the function can be called through that pointer. Function pointers also allow functions to be passed as arguments to other functions.

Pointer as a function parameter list is used to hold the address of argument 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.

Program

#include 
void swap(int *a, int *b); // function prototype

int main()
{
    int p=10, q=20;
    printf("Before Swapping:\n\n");
    printf("p = %d\n",p);
    printf("q = %d\n\n",q);

    swap(&p,&q); //passing address of p and q to the swap function
    printf("After Swapping:\n\n");
    printf("p = %d\n",p);
    printf("q = %d\n",q);
    return 0;
}

//pointer a and b holds and points to the address of p and q
void swap(int *a, int *b)
{
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}

Output

Before Swapping:

p = 10
q = 20

After Swapping:

p = 20
q = 10
Press any key to continue . . .

The address of memory locationmandnare passed to the function swap and the pointers*aand*baccept those values.

So, now the pointeraandbpoints to the address ofmandnrespectively.

When, the value of pointers are changed, the value in the pointed memory location also changes correspondingly.

Hence, changes made to*aand*bare reflected inmandnin the main function.

This technique is known as Call by Reference in C programming.

Simple Example of Pointer to Function

Program

#include 
#include 

int add(int x, int y)
{
 return x+y;
}

int main( )
{
 int (*functionPtr)(int, int);
 int s;
 functionPtr = add;   // 
 s = functionPtr(20, 45);
 printf("Sum is %d",s);
 getch();
 return 0;
}

Output

Sum is 65

Explanation

It is possible to declare a pointer pointing to a function which can then be used as an argument in another function. A pointer to a function is declared as follows,

 type (*pointer-name)(parameter);

Example :
int (*add)();   //legal declaration of pointer to function
int *add();   //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 the function.

int add(int, int);
int (*s)(int, int);
sr = add;

sr is a pointer to a function sum. Now sum can be called using function pointer s with the list of parameter.

sr(10, 20);

Function returning Pointer

A function can also return a pointer to the calling function. In this case you must be careful, because local variables of function doesn't live outside the function. They have scope only till inside the function. Hence if you return a pointer connected to a local variable, that pointer be will pointing to nothing when function ends.

Program

This program will check who is larger among two number, it is not for quality checking

#include 
#include 
int* checklarger(int*, int*);
void main()
{
 int num1 ;
 int num2;
 int *ptr;
 
 printf("Enter Two number: \n");
 scanf("%d %d",&num1,&num2);
 

 
 ptr = checklarger(&num1, &num2);
 printf("%d is larger \n",*ptr);
}

int* checklarger(int *m, int *n)
{
 if(*m > *n)
  return m;
 else
  return n;
}

Output

Enter Two number:
546
1213
1213 is larger
 

Address of the Function

We can fetch the address of an array by the array name, without indexes, Similarly We can fetch the address of a function by using the function's name without any parentheses or arguments. To see how this is done, read the following program, which compares two strings entered by the user. Pay close attention to the declarations of checkString( ) and the function pointer p, inside main( ).

#include 
#include 
void checkString(char *a, char *b,
int (*cmp)(const char *, const char *));

int main(void)
{
	char strng1[80], strng2[80];
	int (*ptr)(const char *, const char *); /* function pointer */
	ptr = strcmp; /* assign address of strcmp to ptr */
	printf("Enter two strings.\n");
	gets(strng1);
	gets(strng2);
	checkString(strng1,strng2,ptr); /* pass address of strcmp via ptr */
	return 0;
}

void checkString(char *m, char *n,
int (*cmp) (const char *, const char *))
{
	printf("Testing for equality.\n");
	
	if(!(*cmp)(m, n)){ printf("Equal \n");
	}
	else{
	 printf("Not Equal \n");
	}
}
Output 1:
Enter two strings.
atnyla
atnyla
Testing for equality.
Equal

Output 1:
Enter two strings.
atnyla
atnlla
Testing for equality.
Not Equal
Press any key to continue . . .

Explanation

First, examine the declaration for ptr in main( ). It is shown here:

int (*ptr)(const char *, const char *);

This declaration tells the compiler that ptr is a pointer to a function that has two const char * parameters, and returns an int result. The parentheses around ptr are necessary in order for the compiler to properly interpret this declaration. You must use a similar form when declaring other function pointers, although the return type and parameters of the function may differ.

void checkString(char *m, char *n,
int (*cmp) (const char *, const char *))

Next, examine the checkString( ) function. It declares three parameters: two character pointers, m and n, and one function pointer, cmp. Notice that the function pointer is declared using the same format as was ptr inside main( ). Thus, cmp is able to receive a pointer to a function that takes two const char * arguments and returns an int result. Like the declaration for ptr, the parentheses around the *cmp are necessary for the compiler to interpret this statement correctly.

When the program begins, it assigns ptr the address of strcmp( ), the standard string comparison function. Next, it prompts the user for two strings, and then it passes pointers to those strings along with ptr to check( ), which compares the strings for equality. Inside checkString( ), the expression

(*cmp)(a, b)

calls strcmp( ), which is pointed to by cmp, with the arguments m and n. The parentheses around *cmp are necessary. This is one way to call a function through a pointer. A second, simpler syntax, as shown here, can also be used.

cmp(a, b);

The reason that you will frequently see the first style is that it tips off anyone reading your code that a function is being called through a pointer (that is, that cmp is a function pointer, not the name of a function). Also, the first style was the form originally specified by C.

Note that you can call checkString( ) by using strcmp( ) directly, as shown here:

checkString(s1, s2, strcmp);

Another Example

Program

#include 
#include 
#include 
#include 
void check(char *a, char *b,
int (*cmp)(const char *, const char *));
int comparevalues(const char *a, const char *b);

int main(void)
{
	char strng1[90], strng2[90];
	printf ("Enter two values or two strings.\n");
	gets(strng1);
	gets(strng2);
	
	if(isdigit(* strng1)) {
	printf("Testing values for equality.\n");
	check(strng1, strng2, comparevalues);
	}
	else {
	printf("Testing strings for equality.\n");
	check(strng1, strng2, strcmp);
	}
	
return 0;
}

void check(char *m, char *n,
int (*cmp)(const char *, const char *))
{
	if(!(*cmp)(m, n)){
	 printf("Equal \n");
	}
	else{
	 printf("Not Equal \n");
	}
}

int comparevalues(const char *m, const char *n)
{
	if(atoi(m)==atoi(n)) return 0;
	else return 1;
}

Output

Output 1:
Enter two values or two strings.
atnyla
atnyla
Testing strings for equality.
Equal

Output 2:
Enter two values or two strings.
atnyla
atnyll
Testing strings for equality.
Not Equal

Output 3:
Enter two values or two strings.
123
155
Testing values for equality.
Not Equal
 
Output 4:
Enter two values or two strings.
055
55
Testing values for equality.
Equal