Search code examples
cstructfunction-pointers

Executing function in C from pointer to function from a struct


I have a struct containing a string and a function pointer, and I am attempting to search for a specific function based on a given string to execute. I am failing to compile, as I am getting assignment errors. I am feeling pretty fried from staring at this all day, so it could easily be something simple. I have tried several different ways to format the struct but I am getting variants on the assignment errors, but I was able to narrow it down to just the return call.

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

Solution

    • In your initialization, don't use the address of operator, just the function identifier (instead of &func_exit, just func_exit).

    • if you dereference a pointer, use the '.' operator, if you are using a pointer use the '->' operator, that said, either *(built_ins + i).func or (built_ins + i)->func or in this case built_ins[i].func

    • the field func is a function pointer, if you want to call that function, you should treat it as a function: built_ins[i].func()

    Why do you pass an array of strings to your function, but use only the first entry?