c - 将函数的地址获取到C中的结构中

标签 c function pointers

typedef void (*MenuItemFunctionPtr) () ; 

struct MenuItem{
    char *TextToDisplayPtr;
    MenuItemFunctionPtr MenuItemFunctionPointer;
    struct MenuItem *NextMenuItem;
    struct MenuItem *SubMenuItem;
};

void MenuItemAFunction ();

我尝试用几种方式定义我的结构:

struct MenuItem MenuItemA = {textA, MenuItemAFunction(), &MenuItemB, 0};
struct MenuItem MenuItemA = {textA, MenuItemAFunction, &MenuItemB, 0};
struct MenuItem MenuItemA = {textA, &MenuItemAFunction(), &MenuItemB, 0};
struct MenuItem MenuItemA = {textA, &MenuItemAFunction, &MenuItemB, 0};

但我总是收到关于函数指针的错误,它们根据我想要定义它的方式而有所不同,所以我想一定有其他方式,但我不知道如何正确地做到这一点。

如何填充 MenuItem 结构?

最佳答案

C 中不推荐使用旧式函数声明。也就是说:

void MenuItemAFunction();

在 C 语言中,MenuItemAFunction 是一个不返回任何内容但接受未知数量的参数或未知类型的函数:声明几乎没有说明参数列表。

声明一个不带参数的函数的正确方法是:

void MenuItemAFunction(void);

Side note: in C++, this is different. The () syntax nicely declares a function with no arguments. Bjarne Stroustrup listened to advisors when he was working on "C with Classes" that became C++. Dennis Ritchie called (void) an "abomination". So Stroustrup was convinced to make () have the obvious meaning.

因此,您可能会得到与此过时用法相关的诊断信息。修复该问题;再试一次。这两个变体应该有效:

struct MenuItem MenuItemA = {textA, MenuItemAFunction, &MenuItemB, 0};
struct MenuItem MenuItemA = {textA, &MenuItemAFunction, &MenuItemB, 0};

address-of & 运算符不是必需的,因为表示函数的表达式(例如由作为函数名称的标识符组成的主函数)已经评估为指针运算符的地址。

如果意图是获取函数的地址,则不希望表达函数调用:不能在 MenuItemAFunction() 周围放置任何语法组合来使指向函数的指针来出于那个表情。

您剩下的“ undefined reference ”错误源于您只声明函数MenuItemAFunction,而不是定义 . 您不能获取不存在的函数的地址。也许您的项目(Makefile、IDE、...)设置不正确,没有在包含该函数定义的源文件中编译和链接。

关于c - 将函数的地址获取到C中的结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22884955/

相关文章:

sql - 我需要在Hive中将小数点位置向左或向右移动而不四舍五入

c - 为什么这对别人有效,对我却无效?

c - 时间(空);与时间(&something);

c - 如何正确传递指向结构的指针

c - 快速阈值和位打包算法(可能的改进?)

c - 在 C 中使用数组(用另一个输入打印一个输入)

javascript - 为什么方法括号内的函数声明会产生 method.variableName()?

JavaScript 实例 : can't define what instance of function's argument is

c++ - 我如何迭代作为指针传递的对数组参数?

c - 如何在输出中获得 0?