coderz.py

Keep Coding Keep Cheering!

Pointers with function in c

Matrix multiplication

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
Syntax of function pointer:
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
Swapping using pointers:
// 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

Follow Me

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

Leave a Comment

Your email address will not be published. Required fields are marked *

Advertisement