c function pointer in struct

How to implement function Pointer in C Struct

Like C++, in C language we cannot create a member function in the structure but with the help of a pointer to a function, we can provide the facility to the user to store the address of the function.

A user can use this structure to store the address of a function using the function pointer as per the requirements and called this function whenever required in the program.

In my previous articles, I have already discussed the function pointer in C and applications of function pointers. Here I am discussing a simple example of how to use the pointer to function in structure.

 

How to use a function pointer in C structure?

The following are the best steps that you should follow to create function pointers within the C structure. These steps might be changed according to the requirements.

Here my requirement is to create a generic function that performs different arithmetic operation

I am recommending that you should use typedef for the aliasing otherwise the prototype become messy. So let’s use how you can implement a function pointer in C struct.

Step 1:

First, you need to declare and aliasing the function pointer as per requirements.  See the below example where I am creating and aliasing two function pointers pfnMessage and pfnCalculator.

//function pointer use to display message
typedef void (*pfnMessage)(const char*,float fResult);


//function pointer use to perform arithmetic operation
typedef float (*pfnCalculator)(float,float);

 

Step-2:

Now create a structure template as your requirement. Here I am creating a structure that contains the above function pointers and float variables.

//structure of function pointer
typedef struct S_sArithMaticOperation
{
    float iResult;
    pfnMessage DisplayMessage;
    pfnCalculator ArithmaticOperation;

} sArithMaticOperation;

 

Step-3:

Now you need to define the function whose address will be held by the created function pointers. You should remember that the prototype of the function pointer and function should be the same.

Here I am defining some arithmetic functions to perform the arithmetic operations. These functions are addition, subtraction, multiplication, and division.

//Perform Addition
float Addition(float a, float b) 
{
    return a + b; 
}


//Perform Subtraction
float Subtraction(float a, float b) 
{
    return a - b; 
}

//Perform Multiplication
float Multiplication(float a, float b)
{
    return a * b; 
}

//Perform Division
float Division(float a, float b)
{
    return (a/b); 
}

 

Steps-4:

In the last, you need to create a generic calculation function that will invoke the desired arithmetic function.  Here I am creating PerformCalculation function which will invoke the arithmetic function and message function which pass by users.

//perform Arithmetic operation
void PerformCalculation(float x, float y, 
                        sArithMaticOperation *funptr,const char *pcMessage)
{
    float result = funptr->ArithmaticOperation(x,y);
    
    funptr->DisplayMessage(pcMessage,result);
}

 

Driver program to demonstrate function pointer in C struct:

The following code explains how a single function (PerformCalculation) performed addition, subtraction, multiplication, and division. You only need to pass the desired arithmetic function with the relevant message function.

Now you are thinking what is the use of this you can do it simple switch case without using any function pointer.

Don’t worry I will explain its importance after the driver code.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

//function pointer to point display message
typedef void (*pfnMessage)(const char*,float fResult);
//function pointer to point arithmetic  function
typedef float (*pfnCalculator)(float,float);


//structure of function pointer
typedef struct S_sArithMaticOperation
{
    float iResult;
    pfnMessage DisplayMessage;
    pfnCalculator ArithmaticOperation;
} sArithMaticOperation;

//Perform Addition
float Addition(float a, float b)
{
    return (a + b);
}

//Perform Subtraction
float Subtraction(float a, float b)
{
    return (a - b);
}

//Perform Multiplication
float Multiplication(float a, float b)
{
    return (a*b);
}

//Perform Division
float Division(float a, float b)
{
    return (a/b);
}

//Function display message
void Message(const char *pcMessage, float fResult)
{
    printf("\n\n  %s = %f\n\n\n\n",pcMessage,fResult);
}

//perform Arithmetic operation
void PerformCalculation(float x, float y, sArithMaticOperation
                        *funptr,const char *pcMessage )
{
    //Call function as per the user choice
    float result = funptr->ArithmaticOperation(x,y);
    //Display the Message
    funptr->DisplayMessage(pcMessage,result);
}

int main()
{
    char szMessage[32] = {0};
    int iChoice = 0;
    float fData1 = 0.0f;
    float fData2 = 0.0f;
    sArithMaticOperation *pS = NULL;

    pS = malloc(sizeof(sArithMaticOperation));
    if (pS == NULL)
    {
        return -1;
    }

    pS->DisplayMessage = &Message;
    while(1)
    {
        printf("\n\n  1.Add \n\
  2.Sub \n\
  3.Mul \n\
  4.Div \n\
  5.Exit \n\n\n");

        printf("  Enter the operation Choice = ");
        scanf("%d",&iChoice);

        switch(iChoice)
        {
        case 1 :
            printf("\n  Enter the numbers : ");
            scanf("%f",&fData1);
            printf("\n  Enter the numbers : ");
            scanf("%f",&fData2);
            pS->ArithmaticOperation = &Addition;
            strcpy(szMessage,"Addition of two Number = ");
            break;

        case 2 :
            printf("\n  Enter the numbers :");
            scanf("%f",&fData1);
            printf("\n  Enter the numbers :");
            scanf("%f",&fData2);
            pS->ArithmaticOperation = &Subtraction;
            strcpy(szMessage,"Subtraction of two Number = ");
            break;

        case 3 :
            printf("\n  Enter the numbers :");
            scanf("%f",&fData1);
            printf("\n  Enter the numbers :");
            scanf("%f",&fData2);
            pS->ArithmaticOperation = &Multiplication;
            strcpy(szMessage,"Multiplication of two Number = ");
            break;

        case 4 :
            printf("\n  Enter the numbers :");
            scanf("%f",&fData1);
            printf("\n  Enter the numbers :");
            scanf("%f",&fData2);
            pS->ArithmaticOperation = &Division;
            strcpy(szMessage,"Division of two Number = ");
            break;

        case 5 :
            printf(" \n Invalid Choice :\n\n");
            exit(0);
        }
        
        //Calling Desire arithmetic function
        PerformCalculation(fData1,fData2,pS,szMessage);
    }
    //Free the allocated memory
    free(pS);

    return 0;
}

OutPut:

User choice: 1

function pointer in C struct

 

 

 

 

 

 

When User choice: 2

function pointer in C struct

 

 

 

 

 

 

Now User choice: 3

function pointer in C struct

 

 

 

 

 

 

 

When User choice: 4

function pointer in structure in C

 

 

 

 

 

 

 

Now it’s time to clear to your doubt why we are using function pointer if we can do it with simple function calling in switch case.

So the answer to your question is that  “YES” here we can accomplish our task by calling the desired function in the switch case. But what happens if someone wants to hide their implementation or only wants to provide the library code.

In that scenario, function pointers will be useful. We use the function pointers when we want to hide our actual implementation from the user and provide the flexibility to them that they can do their task in a defined way.

The best example is the qsort function, the single function can sort array in ascending and descending order only you need to create compare function accordingly.

 

Recommended Articles for you: