gpt4 book ai didi

C 函数指针数组

转载 作者:太空宇宙 更新时间:2023-11-04 05:23:10 25 4
gpt4 key购买 nike

我有三个函数数组,每个都指向多个函数。

我可以调用这三个表中的任何函数。

现在我想将三个数组取消引用为一个函数指针数组,但我就是无法让它工作!

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!!!

最佳答案

两件事:首先要记住,数组自然会退化为指向其第一个元素的指针;其次,如果您为函数类型使用类型别名,它将变得更加容易。

有了这些知识,您就可以做到这一点,例如

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

使用 AllFuncTbls 调用函数非常简单

AllFuncTbls[TblNo][FuncNo]();

关于C 函数指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50524421/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com