简体   繁体   中英

Struct with pointer to function

can you please explain in details this line of code inside struct: There is a pointer to function but why would you reference it to struct?

void (*function)(struct Structure *); 

what does this mean

(struct Structure *)? 
(struct Structure *)

It means that the function have a struct Structure * argument. Actually it will make more sense with (struct Structure *variable of struct) . In this way, you can use a pointer to point a struct and should put the address of the struct variable which can be used in the function.

#include <stdio.h>

typedef struct circle{
    int rad;
    int area;
} Circle;

void ShowCircleInfo(Circle *info)
{
    printf("rad value: %d\n", info->rad);
    printf("area value: %d", info->area);
}

int main(void)
{
    Circle circle_one;
    circle_one.rad = 2;
    circle_one.area = 3;
    ShowCircleInfo(&circle_one);
    
    return 0;
}   

void (*function)(struct Structure *); declares function to be a pointer to a function that has a parameter of type struct Structure * and does not return a value.

For example

#include <stdio.h>

struct Structure {
    int a;
    void (*function)(struct Structure *);
};

void foo(struct Structure *a) {
    if (a->function == NULL) a->function = foo;
    a->a++;
    printf("%d\n", a->a);
}

int main(void) {
    struct Structure a = {42, foo};
    struct Structure b = {0}; // don't call b.function just yet!!
    a.function(&b); // foo(&b)
    b.function(&a); // foo(&a)
}

See code running at https://ideone.com/7E74gb

In C, function pointer declarations have almost the same structure as function headers. Only the function name will change to have some parantheses and a "*" in it, and the arguments won't have names, because only their types are important when using pointers (we don't access the values of the arguments, so we don't need their names).

They basically look like this:

<return_value> (*<function_name>)(<argument_list>)

So, for example, the function pointer for the function

void swap(int* a, int* b);

would be

void (*swap_ptr)(int*, int*);

Notice that the name of the pointer is in the place of the name of the function, and looks a bit odd compared to normal pointer declarations.

An excellent reading on this topic (you can skip the C++ stuff): https://www.cprogramming.com/tutorial/function-pointers.html

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