【问题标题】:Executing function in C from pointer to function from a struct在C中从结构指针到函数执行函数
【发布时间】:2020-11-19 18:42:36
【问题描述】:

我有一个包含字符串和函数指针的结构,我正在尝试根据要执行的给定字符串搜索特定函数。 我无法编译,因为我收到分配错误。整天盯着这个我感觉很煎熬,所以它很容易变得简单。 我尝试了几种不同的方法来格式化结构,但我得到了赋值错误的变体,但我能够将其缩小到仅返回调用。

typedef struct builtin
{
        char *str;
        int (*func)(void);
} built_t;

/**
 * exec_builtin - matches input to function and runs function
 * @argv: null terminated string of args for program
 * Return: 1 on success, 0 on exit, -1 on failure
 */

int exec_builtin(char **commands)
{
        built_t built_ins[] = {
                {"exit", &func_exit},
                {NULL, NULL}
        };

        int i = 0, function;

        for (i = 0; built_ins[i].str != NULL; i++)
                if (strcmp(built_ins[i].str, commands[0]) == 0)
                {
                        function = *(built_ins + i)->func;
                        return (function);
                }
        return (-1);
}

【问题讨论】:

    标签: c struct function-pointers


    【解决方案1】:
    • 在你的初始化中,不要使用操作符的地址,只使用函数标识符(而不是&func_exit,只使用func_exit)。

    • 如果你取消引用一个指针,使用'.'运算符,如果您使用指针,请使用 '->' 运算符,即 *(built_ins + i).func 或 (built_ins + i)->func 或在本例中为 built_ins[i].func

    • 字段func是一个函数指针,如果你想调用那个函数,你应该把它当作一个函数:built_ins[i].func()

    为什么你将一个字符串数组传递给你的函数,但只使用第一个条目?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-21
      • 2021-01-26
      • 1970-01-01
      • 2015-06-12
      • 1970-01-01
      相关资源
      最近更新 更多