【问题标题】:call a function, pointed by a function pointer member in a structure array调用由结构体数组中的函数指针成员指向的函数
【发布时间】:2014-08-05 10:17:22
【问题描述】:

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

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

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

我的代码是:

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() 谢谢大家!

【问题讨论】:

  • 那么最后一步,告诉我们会发生什么。顺便说一句,您不妨将BtnStruct *BtnStructArray[2] 更改为BtnStruct BtnStructArray[2]。声明一个指针数组和一对实例(Btn0Btn1),然后设置BtnStructArray[0] = &Btn0BtnStructArray[1] = &Btn1 似乎没有任何意义。
  • 似乎对我来说是正确的称呼ideone.com/jUQy5F
  • 你应该像这样初始化BtnStructArray[0]->eventhandler = function0; ,函数指针在main()之后。你不应该全局初始化它们。

标签: c arrays structure function-pointers


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    相关资源
    最近更新 更多