Search code examples
cfunction-pointers

How to declare a function pointer?


I came across these two programs:

int* getb(int* p);
void main()
{
    int x = 5 ;
    int* ptr = getb(&x);
    printf("%d\n",*ptr);
}

int* getb(int* p)
{
    int* re = (int*)malloc(1*sizeof(int));
    *re = *p *= 2;
    return re;
}
void fun(int a) 
{ 
    printf("Value of a is %d\n", a); 
} 

int main() 
{ 

    void (*fun_ptr)(int) = &fun; 

    (*fun_ptr)(10); 

    return 0; 
} 

What is the difference between the function pointer declarations in the two programs?

int* getb(int* p);

and

void (*fun_ptr)(int) = &fun; 

Solution

  • int* getb(int* p);
    

    This is not a function pointer, it's a function prototype. C compilers don't "look ahead" for functions, so if you're calling a function that hasn't been defined yet you need to put a prototype that lists the function's parameters and return type above the call site. That's what's happening in the first program.

    void (*fun_ptr)(int) = &fun; 
    

    This is a function pointer. It creates a variable named fun_ptr that points to the function fun().