Function pointers inside a structure, but with functions of different prototypes in C

Suppose I have functions:

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

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

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

And I will say that I want to have a pointer to a function inside the structure:

for instance

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 follows:

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() > ??

... etc...

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

+5
source share
2 answers

I would use function pointers union:

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

You will also need a field in the structure to indicate which one is being used.

+7
source

You have two options - sloppy, but easy or accurate, 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 },
};

, -Wstrict-prototypes GCC. , , - char **pname, , , .

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 },
};

, C99. .

+2

All Articles