gpt4 book ai didi

调用由结构体数组中的函数指针成员指向的函数

转载 作者:行者123 更新时间:2023-11-30 17:30:28 25 4
gpt4 key购买 nike

我想调用一个由结构体数组中的函数指针成员指向的函数。

在运行时,我想对函数指针排序不同的函数。

不知何故,这些函数没有被调用。你能解释一下吗,为什么?

我的代码是:

typedef struct 
{
char c; // several simple type variables...
int(*eventhandler)(int param); // function pointer member (maybe, it would do with double indirection...?)
} BtnStruct;

BtnStruct Btn0; // BtnStruct variable
BtnStruct Btn1;

BtnStruct *BtnStructArray[2]; // array of pointers, pointed to BtnStruct type variables

BtnStructArray[0] = &Btn0; // fill the array with addresses of BtnStruct variables
BtnStructArray[1] = &Btn1;

int returnvalue; // just for test

int function0(int param) // say, there is a similar function1()
{
int retval;

// do something

return(retval);
}

// In Run time:

BtnStructArray[0]->eventhandler = function0; // I try to give the address of the function, to the function pointer member
BtnStructArray[1]->eventhandler = function1;


returnvalue = BtnStructArray[0]->eventhandler(10); // here I want to call the pointed function with parameter
// But the function is not invoked

解决了! :)

我忘记了“function0”之前的“&”。这就是错误。

正确的是:

BtnStructArray[0]->eventhandler = &function0;

致巴拉克:感谢您的提示,但由于某些原因,我必须使用指针数组,而不是简单的结构数组。但是你帮助了我,因为当我测试你的更简单的版本时,我发现了错误。 :)

致阿斯克米什:也许,我粘贴的代码不清楚。当然,我初始化了函数指针,但正如我上面所写的,我犯了一个错误。

致巴巴卡尔·迪亚塞:是的,“运行时”的意思是,下一个代码在 main() 中,谢谢大家!

最佳答案

您只能在“运行时”内单独初始化数组(我想您的运行时是 main() 或 main() 调用的函数。)或者,您可以这样做来初始化他们在声明中:

BtnStruct *BtnStructArray[2] = {&Btn0, &Btn1}

关于调用由结构体数组中的函数指针成员指向的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25136367/

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