简体   繁体   English

如何将函数指针分配给函数

[英]How to assign function pointer to a function

I have this program and I'm getting: 我有这个程序,我得到:

lvalue required as left operand of assignment 需要左值作为赋值左操作数

because of the line function_a = function . 由于行function_a = function

int function_a(int j){
    return j+10;
}

int function_b(int j){
    return j;
}

void set_a(int (*function)(int)){
    function_a = function;
}

int main(){
    int a = function_a(2);
    printf("%d, ", a);

    set_a(function_b);

    int b = function_a(2);
    printf("%d", b);
}

I want to set function_a to function_b in function set_a . 我想设置function_afunction_b在功能set_a So I'm expecting output 12, 2 . 所以我很期待输出12, 2 What I should do to assign this properly? 我应该怎么做才能正确地分配这个?

A function definition cannot be replaced by assignment, ie a function definition is not an lvalue to which you can assign something, and that's why you get the error; 函数定义不能用赋值代替,即函数定义不是可以赋值的左值,这就是为什么会出现错误。 But you can define a function pointer and assign different function definitions, and call the function pointer just as if it were a function in the sense of an ordinary function definition: 但是您可以定义一个函数指针并分配不同的函数定义,然后像在普通函数定义的意义上一样调用该函数指针:

int function_a(int j){
    return j+10;
}

int function_b(int j){
    return j;
}

int (*f)(int) = function_a;

void set_a(int (*function)(int)){
    f = function;
}


int main(int argc, const char *argv[])
{

    int a = f(2);
    printf("%d, ", a);

    set_a(function_b);

    int b = f(2);
    printf("%d", b);

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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