Is it right to pass a function to a structure?

I looked, but could not find a direct link to this question. I'm new to function pointers (and C), so I don't know all the tricks that can still be done :)

I really got the function:

void select_comparator(My_Struct *structure, int (*comp)(int x, int y)) {
    ...

... where it My_Structhas a prototype:

typedef struct my_struct {
    int (*comp)(int x, int y);
} My_Struct;

Change some small details. I just want to know if the following is the correct syntax:

void select_comparator(My_Struct *structure, int (*comp)(int x, int y)) {
    structure->comp = comp;
}

It seems to be too easy, and I'm worried.

+4
source share
2 answers

: c. , , . , , , void, ..


/*******************************************************************************
 * Preprocessor directives.
 ******************************************************************************/
#include <stdio.h>


/*******************************************************************************
 * Data types.
 ******************************************************************************/
typedef struct my_struct {
    int (*comp)(int x, int y);
} My_Struct;


/*******************************************************************************
 * Function prototypes.
 ******************************************************************************/
int c(int a, int b);
void select_comparator(My_Struct *structure, int (*comp)(int x, int y));


/*******************************************************************************
 * Function definitions.
 ******************************************************************************/
/*----------------------------------------------------------------------------*/
int main(void)
{
    My_Struct s;

    select_comparator(&s, &c);
    s.comp(1, 2);

    return 0;
}

/*----------------------------------------------------------------------------*/
void select_comparator(My_Struct *structure, int (*comp)(int x, int y))
{
    structure->comp = comp;
}

/*----------------------------------------------------------------------------*/
int c(int a, int b)
{
    int ret = 0;
    if (a < b) {
        ret = (-1);
    } else if (a > b) {
        ret = 1;
    }

    return ret;
}
+3

.

, C, / . - , -, - , , - .

" " , typedefs.

:

typedef int comp_t (int x, int y); // typedef a function type

typedef struct {
    comp_t* comp;   // pointer to such a function type
} My_Struct;

void select_comparator(My_Struct *structure, comp_t* comp) {
    structure->comp = comp;
}

, , .

+1

Source: https://habr.com/ru/post/1680846/


All Articles