Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/articles/cpp-tutorials/)
-   -   How to declare function pointer in structure call it (http://www.go4expert.com/articles/declare-function-pointer-structure-t5851/)

sanjaik 14Aug2007 14:51

How to declare function pointer in structure call it
 
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);
}


shabbir 14Aug2007 15:50

Re: How to declare function pointer in structure call it
 
Nice one but do not have it as a comment in some other article.

shabbir 14Aug2007 16:04

Re: How to declare function pointer in structure call it
 
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.

sanjaik 17Sep2007 17:12

Re: How to declare function pointer in structure call it
 
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


All times are GMT +5.5. The time now is 20:09.