Server Help

Trash Talk - C / C++ question

Bak - Wed Aug 03, 2005 1:36 am
Post subject: C / C++ question
How would one declare a const array of function pointers? I played with this thing for 10 minutes and couldn't get it compiling. Had to settle for making a wrapper struct for the function pointer, then making an array of structs.

I guess a typedef would work too... but seems like it shouldn't be necessary.
Mr Ekted - Wed Aug 03, 2005 1:48 am
Post subject:
const int (*fp[10])(int);

Each function has the form:

int f0 (int) { }
Mine GO BOOM - Wed Aug 03, 2005 1:49 am
Post subject:
Code: Show/Hide
#include <stdio.h>

int main()
{
        void *fList[2];
        fList[0] = printf;
        fList[1] = main;

        printf("Location of printf: %p\n", printf);
        printf("Location of main: %p\n", main);
        printf("Location of fList[0]: %p\n", fList[0]);
        printf("Location of fList[1]: %p\n", fList[1]);

        return 0;
}

Code: Show/Hide
Location of printf: 0x80482a8
Location of main: 0x8048384
Location of fList[0]: 0x80482a8
Location of fList[1]: 0x8048384

Worked fine for me. Requires you to typecast it correctly when you use it though. If all the functions are the same style, use Ekted's method.
Bak - Wed Aug 03, 2005 1:57 am
Post subject:
That works.
Bak - Wed Aug 03, 2005 2:07 am
Post subject:
Looks like I spoke too soon.

when you do const int (*fp[10])(int); it thinks the function is returning a const int, rather than the array is a const

For example this won't compile:
Code: Show/Hide

int (*f)(int) = 0;
int (*f2)(int) = 0;

const int (*fp[2])(int) =
{
   f,
   f2
};


got it to work though, you need
Code: Show/Hide

int (*const fp[2])(int) =
{
   f,
   f2
};

Mr Ekted - Wed Aug 03, 2005 3:03 am
Post subject:
You could also typedef a function pointer, then declare a const array of that type.
Cyan~Fire - Wed Aug 03, 2005 10:36 am
Post subject:
Ekted wrote:
You could also typedef a function pointer, then declare a const array of that type.

Yeah, that is most definitely what I would do. It seems that writing it like that helps overcome per-compiler differences, too.

Code: Show/Hide
   typedef void (__stdcall * template_func)(AnonymousStruct *);
   template_func RPC[256];
   // void (__stdcall * RPC [256])(AnonymousStruct *);

The commented line only works in MSVC. The two uncommented work in MSVC and MinGW.
All times are -5 GMT
View topic
Powered by phpBB 2.0 .0.11 © 2001 phpBB Group