简体   繁体   中英

C arrays of function pointers

I have three function arrays each pointing to a number of functions.

I can call any of those functions form the three tables.

Now I would like to dereference the three arrays into a single array of function pointers but I just can't get it working!

void afunc1(void);
void afunc2(void);
void afunc3(void);
void bfunc1(void);
void bfunc2(void);
void bfunc3(void);
void cfunc1(void);
void cfunc2(void);
void cfunc3(void);

void(*FuncTbla[])(void) = { afunc1, afunc2, afunc3 };
void(*FuncTblb[])(void) = { bfunc1, bfunc2, bfunc3 };
void(*FuncTblc[])(void) = { cfunc1, cfunc2, cfunc3 };

void (*AllFuncTbls[])(void) = { &FuncTbla, &FuncTblb, &FuncTblc };

int TblNo = 1, FuncNo = 1; // tblNo 1 = table b

bFunc2(); // calls bFunc2 directly

FuncTblb[FuncNo](); // Calls Function bFunc2 via function table b

// Call same function using table of function tables
AllFuncTbls[TblNo][FuncNo](); // Does not compile - expression must be a pointer to a complete object type!!!

Two things: First of all remember that arrays naturally decays to pointers to their first element; And secondly it will become so much easier if you use type-aliases for the function types.

Armed with that knowledge you could do it like eg

// Type-alias to simplify using function pointers
typedef void (*function_type)(void);

// The three tables
function_type FuncTbla[] = { &afunc1, &afunc2, &afunc3 };
function_type FuncTblb[] = { &bfunc1, &bfunc2, &bfunc3 };
function_type FuncTblc[] = { &cfunc1, &cfunc2, &cfunc3 };

// A table of pointers to the first elements of each array
function_type *AllFuncTbls[] = { FuncTbla, FuncTblb, FuncTblc };

To call a function using AllFuncTbls is as simple as

AllFuncTbls[TblNo][FuncNo]();

If you use typedefs it works:

void afunc1(void);
// ...

typedef void (*funcPtr)(void);
// void(*FuncTbla[])(void) = { afunc1, afunc2, afunc3 };
// ...
funcPtr FuncTbla[] = { afunc1, afunc2, afunc3 };
funcPtr FuncTblb[] = { bfunc1, bfunc2, bfunc3 };
funcPtr FuncTblc[] = { cfunc1, cfunc2, cfunc3 };

//void (*AllFuncTbls[])(void) = { &FuncTbla, &FuncTblb, &FuncTblc };
funcPtr* AllFuncTbls[] = { FuncTbla, FuncTblb, FuncTblc };
// Use an Array of pointers to function pointers here, not an array of function pointers!

// ...    

// Call same function using table of function tables
AllFuncTbls[TblNo][FuncNo](); // Compiles now

I commented out the lines that had to be changed.

使用typealiases是更好的方法,但是如果您好奇没有它怎么做:

void(**AllFuncTbls[])(void) = { FuncTbla, FuncTblb, FuncTblc};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM