Home > Software design >  Struct with pointer to function
Struct with pointer to function

Time:05-02

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 *)? 

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

  • Related