C语言中的函数数组,带有空指针参数,按动态分配

42fyovps  于 2023-04-11  发布在  其他
关注(0)|答案(2)|浏览(108)

我不能声明如何正确地声明一个函数vector,我可以将其作为参数传递给get_operations函数,然后我可以在我之前声明的vector的组件的帮助下调用8个函数。下面是我使用的结构和函数:

void get_operations(void **operations) {
    operations[0] = tire_pressure_status;
    operations[1] = tire_temperature_status;
    operations[2] = tire_wear_level_status;
    operations[3] = tire_performance_score;
    operations[4] = pmu_compute_power;
    operations[5] = pmu_regenerate_energy;
    operations[6] = pmu_get_energy_usage;
    operations[7] = pmu_is_battery_healthy;
}
4ngedf3f

4ngedf3f1#

1.定义一个函数指针typedef:typedef void (*function_ptr_t)(void)
1.相应地修改您的函数:

void get_operations(function_ptr_t *operations) {
   operations[0] = tire_pressure_status;
   ...
}

1.使用typedef创建一个函数指针数组作为函数向量:function_ptr_t operations[8]
1.将数组传递给get_operations

pcrecxhr

pcrecxhr2#

typedef int (*statfunc)(void *);

int tire_pressure_status(void *);
int tire_temperature_status(void *);
int tire_wear_level_status(void *);
int tire_performance_score(void *);

void get_operations(void **operations) {
    statfunc *vect = *operations;
    vect[0] = tire_pressure_status;
    vect[1] = tire_temperature_status;
    vect[2] = tire_wear_level_status;
    vect[3] = tire_performance_score;
}

int main(void)
{
    statfunc vector[4];
    void *ptr_to_vector = vector;

    get_operations(&ptr_to_vector);

    vector[0](NULL);
    vector[1](NULL);
    vector[2](NULL);
    vector[3](NULL);
}

int tire_pressure_status(void *)
{
    return printf("%s\n", __func__);
}

int tire_temperature_status(void *)
{
    return printf("%s\n", __func__);
}

int tire_wear_level_status(void *)
{
    return printf("%s\n", __func__);
}

int tire_performance_score(void *)
{
    return printf("%s\n", __func__);
}

https://godbolt.org/z/1nTPKd8v1

相关问题