Test065
Test065

Reputation: 49

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; 

Upvotes: 0

Views: 1154

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 310940

This declaration

int* getb(int* p);

is not a declaration of a function pointer. It is a declaration of a function that has the return type pointer to int that is int * and one parameter of the same type: pointer to int.

The function type is

int * ( int * )

To declare a pointer to the function type you have to write for example

int * ( *fun_ptr )( int * ) = getb;

This declaration

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

is indeed a declaration of a pointer to function type void( int ) that is initialized by the address of the function fun.

You could write

void (*fun_ptr)(int) = fun;

because function designators used in expressions are converted to pointers to the functions.

And to call the function used as an initiliazer of the pointer fun_ptr you could just write

fun_ptr(10);

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 361585

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().

Upvotes: 2

Dai
Dai

Reputation: 155055

int* getb(int* p)

This is not a function-pointer declaration. It's a forward declaration of the getb function.

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

This is a function-pointer variable declaration.

Note that in C, the address-of operator & is implicit, so these two statements behave the same:

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

void (*fun_ptr)(int) = fun; 

See here: Function pointers and address of a function

Upvotes: 1

Related Questions