Roulians
Roulians

Reputation: 23

Array of structures of function pointers C

I'm trying to initialize an array of structures containing pointer on function :

typedef struct struct_actioncommand {
    char *action;
    void (*command)(my_type);
} type_actioncommand;

To initialize each pointer with its function name I'm using this method :

static const type_actioncommand g_cmd_tab[] = {
    {"Action1", function1},
    {"Action2", function2},
    {"Action3", function3},
    {NULL, NULL}
};

But it doesn't work. When I try to compile with "gcc", I have the following message:

myfile.c:16:3: error: initialization from incompatible pointer type [-Werror]
{"Action1", function1},
^
myfile.c:16:3: error: (near initialization for g_cmd_tab[0].command) [-Werror]
myfile.c:17:3: error: initialization from incompatible pointer type [-Werror]
{"Action2", function2},
^
myfile.c:17:3: error: (near initialization for g_cmd_tab[1].command) [-Werror]
myfile.c:18:3: error: initialization from incompatible pointer type [-Werror]
{"Action3", function3},
^
myfile.c:18:3: error: (near initialization for g_cmd_tab[2].command) [-Werror]
cc1: all warnings being treated as errors

each function is defined according to this prototype :

void function1(my_type *var1);

I'm a little bit confuse now since I dont see how to fix my problem. Any ideas?

Upvotes: 2

Views: 215

Answers (1)

dbush
dbush

Reputation: 223917

In your struct, the command member:

void (*command)(my_type);

Has type "pointer to function which take a parameter of type my_type and returns void.

Your function:

void function1(my_type *var1);

Has type "function which takes a parameter of type my_type * and returns void.

The parameters of the function pointer don't match the parameters of the functions you assign to them. That makes the pointers incompatible.

To fix this, change the type of the function pointer to match the functions that are assigned to it:

void (*command)(my_type *);

Upvotes: 2

Related Questions