2

is there any possibility for function pointer for addressing function with different no of arguments of same return type, if not any alternate would be helpful.. thanks in advance

example:

struct method
{
    char *name;
    void (*ptr)(?);  //? : what to define as arguments for this
};

void fun1(char *name)
{
    printf("name %s\n\r",name);
}
void fun2(char *name, int a)
{
    printf("name %s %d\n\r",name,a);
}

//defined before main()
method def[]=
{
    {"fun1",fun1},
    {"fun2",fun2}
}
//some where in main()
//call for function pointer
def[1].ptr("try", 2);
2
  • 1
    You can only use pointers to functions for functions that have the same function signature. Commented Jan 16, 2014 at 12:45
  • This looks like a parsing problem failing in the very beginning: en.wikipedia.org/wiki/… Commented Jan 16, 2014 at 12:58

3 Answers 3

0
typedef void (*myfunc)(char *,int);

struct method
{
    char *name;
    myfunc ptr;  
};

method def[]=
{
     //we store fun1 as myfun 
     //type void(char*,int) and use it this way
    {"fun1",(myfunc)fun1},
    {"fun2",fun2}
};

This is by theory undefined behavior, but in reality it should work on most platforms
* edit -> this works on all plaforms just like printf(const char*,...) does.

Sign up to request clarification or add additional context in comments.

Comments

0

In C, you can make your function pointer declaration read

void (*ptr)(); 

Which means 'A pointer to a function returning void and expecting an unspecified number of argments.'

With that adjustement, your sample program works as expected to me. However, it may well be that you're venturing into undefined (or at least implementation defined) lands here - I don't know for sure and I'm not a language lawyer (however there are plenty of language lawyers frequenting SO, so I'm sure somebody can whip up the relevant section of the standard or prove that there is none). So maybe you should rather use

/* Here be dragons! */
void (*ptr)();

instead.

Comments

0

Solution #1:

void fun1(char *name, ...);
void fun2(char *name, ...);

Solution #2:

method def[]=
{
    {"fun1",printf},
    {"fun2",printf}
}

2 Comments

Of course, in the first solution, you will have to work "hard" on the internal implementation of these two functions
what if in some functions there are no parameters.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.