首页 > 解决方案 > Using a function from a function array stored in a struct in C

问题描述

I declared a struct like this one :

typedef struct s_data {

    char buff[2048];
    int len; 
    void *func[10];
    struct data *next;

}               t_data;

In my code, when passing a *data, I assigned some functions (just giving one so it is more understandable)

void init_data(t_data *data)
{
    data->len = 0;
    data->func[0] = &myfirstfunctions;
    //doing the same for 9 others

}

My first function would be something taking as argument *data, and an int. Then, I try to use this function in another function, doing

data->func[0](data, var);

I tried this and a couple of other syntaxes involving trying to adress (*func[0]) but none of them work. I kind of understood from other much more complex questions over there that I shouldn't store my function like this, or should cast it in another typedef, but I did not really understand everything as I am kind of new in programming.

标签: arrayscstructurefunction-pointers

解决方案


void* can only be used reliably as a generic object pointer ("pointer to variables"). Not as a generic function pointer.

You can however convert between different function pointer types safely, as long as you only call the actual function with the correct type. So it is possible to do just use any function pointer type as the generic one, like this:

void (*func[10])(void);
...
func[0] =  ((void)(*)(void))&myfirstfunction;
...
((whatever)func[0]) (arguments); // call the function

As you might note, the function pointer syntax in C is horrible. So I'd recommend using typedefs:

typedef void genfunc_t (void);
typedef int  somefunc_t (whatever*); // assuming this is the type of myfirstfunction

Then the code turns far easier to read and write:

genfunc_t* func [10];
...
func[0] = (genfunc_t*)&myfirstfunction;
...
((somefunc_t*)func[0]) (arguments);

推荐阅读