简体   繁体   中英

Structure of pointers to function

if I have a structure that has a pointer to a function like this

struct str{
 int some_element;
 char other_element;
 int (*my_pointer_to_a_function)(int);
};

struct str my_struct;
int my_function(int);

and I asign values to it

my_struct.some_element = 1;
my_struct.other_element = 'a';
my_struct.my_pointer_to_a_function = my_function;

how do I call the function that the pointer is pointing to (using the pointer)? My initial guess is this:

my_struct.(*my_pointer_to_a_function)(value);

or should it be

 *my_struct.my_pointer_to_a_function(value);

?

Thank you.

Pointers to functions can be used as-is, without any dereference:

my_struct.my_pointer_to_a_function(value)

But if you insist in dereferencing it you have to use parenthesis this way:

(*my_struct.my_pointer_to_a_function)(value)

They both are totally equivalent, so I recommend the first one, that is simpler.

About you first try:

my_struct.(*my_pointer_to_a_function)(value); //Error!

That won't work because the expression in parenthersis has to be evaluated first: *my_pointer_to_a_function , but that alone means nothing.

And your second:

*my_struct.my_pointer_to_a_function(value); //Error!

The operator precedence rules evaluates first the . , then the function call, and lastly the * :

*(my_struct.my_pointer_to_a_function(value)); //Error!

So the function would be called, but the result of the call, an int , would be dereferenced, hence the error.

Suppose you have pointer to function as you struct member like:

    struct newtype{
        int a;
        char c;
        int (*f)(struct newtype*);
    } var;
    int fun(struct newtype* v){
        return v->a;
    }

You can call it as follows:

    int main(){
        var.f=fun;
        var.f(&var);
     //  ^.....^..... have to pass `var` as an argument to f() :( :(
    }

 //Comment: here in var.f(&var); I miss this pointer and C++,      

So for your case it should be just my_struct.my_pointer_to_a_function(value);

Additionally points:
Important to note in my example even you wants to access members of same structure variable you have to pass that. (its quite dissimilar than c++ object!)
virtual functions in C++ classes. They are implemented in a similar fashion under the hood.

Here is a project that will help you to use: Function pointers inside structures

Use this:

#define function mystruct.my_pointer_to_a_function

Then you can call the function :

int i = function(value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM