We can create a pointer pointing to a function in the same way that we can create a pointer of any data type, such as int , char, or float.
A function’s code is always stored in memory, which implies that the function has an address. We use the function pointer to get the memory address.
For instance:
#include <stdio.h>
void square(int a){
printf("%d",a*a);
}
int main()
{
printf("Address of main() function is %p",main);
printf("\nAddress of square() function is %p",square);
return 0;
}
Output:
Address of main() function is 0x55aa5e80d174
Address of square() function is 0x55aa5e80d149
return type (*p_name)(type1, type2…);
For example:
float (*f)(float);
*f is a pointer that points to a function that returns a float value and accepts a float value as an argument.
Let’s understand the function pointer through an example.
#include <stdio.h>
int add(int,int);
int main()
{
int a,b;
int (*p)(int,int);
int result;
printf("Enter the values of a and b : ");
scanf("%d %d",&a,&b);
p=add;
result=(*p)(a,b);
printf("Value after addition is : %d",result);
return 0;
}
int add(int a,int b)
{
int c=a+b;
return c;
}
output:
Enter the values of a and b : 23 56
Value after addition is : 79
// function to swap the two numbers
void swap(int *x,int *y)
{
int t;
t = *x;
*x = *y;
*y = t;
}
int main()
{
int num1,num2;
printf("Enter value of num1: ");
scanf("%d",&num1);
printf("Enter value of num2: ");
scanf("%d",&num2);
//displaying numbers before swapping
printf("Before Swapping: num1 is: %d, num2 is: %d\n",num1,num2);
//calling the user defined function swap()
swap(&num1,&num2);
//displaying numbers after swapping
printf("After Swapping: num1 is: %d, num2 is: %d\n",num1,num2);
return 0;
}
output:
Enter value of num1: 21
Enter value of num2: 45
Before Swapping: num1 is: 21, num2 is: 45
After Swapping: num1 is: 45, num2 is: 21
Note: also read about the Pointer to Pointer in C
If you like my post please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…