• C

pointers to functons

I want to maintain an array of pointers to functions(functions of different types). Is it possible to
cast a pointer to void to a pointer to a function.
If yes than how?
pelegsAsked:
Who is Participating?
 
alexoConnect With a Mentor Commented:
It is not allowad by ANSI C but many compilers implement it as an extention.

Example comming...
0
 
alexoCommented:
   int f1(int x, int y) { return x + y; }
    void f2(float* p) { *p *= 12; }

    typedef int (*PF1)(int, int);
    typedef void (*PF2)(float*);

    void main()
    {
        void* p;
        int i;
        float f = 1.0;

        p = f1;
        i = ((PF1)p)(2, 3);

        p = f2;
        ((PF2)p)(&f);
    }

Under MSVC there are two warnings:
  warning C4152: nonstandard extension, function/data pointer conversion in expression
  warning C4055: 'abstract declarator' : from data pointer 'void *' to function pointer 'void (__cdecl *)(float )'

However, there's a way to avoid them...
0
 
alexoCommented:
The problem is that ANSI C does not like convertions from data to function pointers and vice versa.  However, if we declare p to be a function pointer (any type) then it is OK.

Example:

    int f1(int x, int y) { return x + y; }
    void f2(float* p) { *p *= 12; }

    typedef int (*PF1)(int, int);
    typedef void (*PF2)(float*);

    void main()
    {
        void (*p)(); /* this line changed */
        int i;
        float f = 1.0;

        p = f1;
        i = ((PF1)p)(2, 3);

        p = f2;
        ((PF2)p)(&f);
    }

0
 
alexoCommented:
So the general answer is: Yes, if the pointer is of the right type to begin with (not a void pointer but a pointer to some function type).
0
 
alexoCommented:
1 more to 50K.  Thank you for participating :-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.