How to declare function pointer in structure call it

sanjaik's Avatar author of How to declare function pointer in structure call it
This is an article on How to declare function pointer in structure call it in C++.
Function pointer - how to declare function pointer in structure and how it call ,see it.
Code: Cpp
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct strfunptr
{
    float   a;
    float   b;
    float (*Func)(float,float);

}sfptr;

float Plus(float a, float b)
{
    return a + b;
}
float Minus(float a, float b)
{
    return a - b;
}
float Mult(float a, float b)
{
    return a * b;
}

float Div(float a, float b)
{
    return a / b;
}

void Switch_With_Function_Pointer(struct strfunptr *);

int main()
{
    sfptr *ptr;

    ptr = (struct strfunptr*)malloc(sizeof(ptr));
    char ch;

    do
    {
        printf("1.Add \n");
        printf("2.Sub \n");
        printf("3.Mul \n");
        printf("4.Div \n");
   
        printf("Enter the operation Choice\n");
        scanf("%d",&ch);

        switch(ch)
        {
            case 1 : printf(" \n Enter the numbers :");
                     scanf("%f %f",&ptr->a,&ptr->b);
                     ptr->Func = Plus;
                     break;

            case 2 : printf(" \n Enter the numbers :");
                     scanf("%f %f",&ptr->a,&ptr->b);
                     ptr->Func = Minus;
                     break;

            case 3 : printf("\n Enter the numbers :");
                     scanf("%f %f",&ptr->a,&ptr->b);
                     ptr->Func = Mult;
                     break;
            case 4 : printf(" \n Enter the numbers :");
                     scanf("%f %f",&ptr->a,&ptr->b);
         ptr->Func = Div;
                     break;

            default :
                printf(" \n Invalid Choice :");
                exit(0);
        }
        Switch_With_Function_Pointer(ptr);

    }while(1);

    return 0;
}

void Switch_With_Function_Pointer(struct strfunptr *funptr )
{
    float result = funptr->Func(funptr->a,funptr->b);
    printf("Switch with function result is :%f\n",result);
}
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Nice one but do not have it as a comment in some other article.
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Quote:
Originally Posted by shabbir
Nice one but do not have it as a comment in some other article.
I just happen to browse through your other posts and it looks like you just posted the above in the wrong window.
0
sanjaik's Avatar
Light Poster
Quote:
Originally Posted by shabbir
Nice one but do not have it as a comment in some other article.
Yes Sir,
You r right. i will try to next time every article with proper comments