5

Suppose I have functions:

void func1(int x)
{
    ....
}

void func2(int x, int y)
{
    ....
}

void func3(int x, int y, int z)
{
    ....
}

And say that I want to have a function pointer within a struct:

For example

typedef struct{
     char *ename;
     char **pname;
    < and here I want to have a function pointer> ??
} Example;

Example ex[3];

Now, I want to populate the ex[3] array as:

ex[0].ename = "X0";
ex[0].pname[0]="A0";
ex[0].pname[1]="B0";
ex[0].<function pointer to func1() > ??


ex[1].ename = "X1";
ex[1].pname[0]="A1";
ex[1].pname[1]="B1";
ex[1].<function pointer to func2() > ??

... and so on...

Is it possible to create something like this? Please help me with this. Thanks.

1
  • Sanity Check: When you decide to call that function, how will you "know" how many operands to pass it? Commented Mar 2, 2012 at 15:30

2 Answers 2

7

I would use a union of function pointers:

union {
    void (*fun1)(int);
    void (*fun2)(int, int);
} fptr;

You also need a field in the struct to tell which is used.

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

Comments

3

You have two choices - sloppy but easy, or exact but painstaking.

Sloppy

typedef struct{
     char *ename;
     char *pname[3];
     void (*function)();   // Pointer to function taking indeterminate arguments
} Example;

Example ex[3] =
{
    { "func1", { "x",           }, func1 },
    { "func2", { "x", "y",      }, func2 },
    { "func3", { "x", "y", "z", }, func3 },
};

This doesn't pass muster if you compile with -Wstrict-prototypes in GCC. Notice that I made sure there was storage for the parameter names - your original had char **pname which would mean you have to allocate the storage for the arrays before assigning the names.

Painstaking

typedef struct{
     char *ename;
     char *pname[3];
     union
     {
         void (*f1)(int x);
         void (*f2)(int x, int y);
         void (*f3)(int x, int y, int z);
     } u;
} Example;

Example ex[3] =
{
    { "func1", { "x",           }, .u.f1 = func1 },
    { "func2", { "x", "y",      }, .u.f2 = func2 },
    { "func3", { "x", "y", "z", }, .u.f3 = func3 },
};

This uses C99 designated initializers to do the initializing. It assigns each function pointer to the correctly typed element of the union.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.