Aakash Aakash - 10 months ago 57
C Question

How can I use variable p to declare a new pointer to function using following

I have


typedef int (*p)();

Let's say the function to which I want to declare a pointer is
int foo()
I wanna declare a new pointer to function foo using variable p to make use of typedef statement like:

typedef int emp[10];
emp p;// so now p is an array of size 10 of type int

Answer Source
  1. p is:

    typedef int (*p) ();
  2. foo() is:

    int foo(){
  3. p type variable is f:

    p  f = &foo; 
  4. how to call using pointer:


Example code:

int foo(){
 printf("\n In FOO\n");
 return 4;
typedef int(*p)();

int main(){
 p f = &foo;
 int i = (*f)();
 printf("\n i = %d\n", i);
 return 1;

you can find it is working on codepad.

note: you can simply assign like p f = foo; and call like f() the second form you can find here on codepad

Edit: As @Akash commented:

it compiles and runs like:

~$ gcc x.c -Wall 
~$ ./a.out 
 i = 4

Here is a project to help explain the usefulness of function pointers.