0

I'm trying to get this code to run..

#include <stdio.h> 

int *myMethod(int *a) 
{ 
   printf("Hello");
   return a; 
} 

int main() 
{ 
    // my_ptr is a pointer to function myMethod() 
    int *my_ptr(int *) = myMethod; 

    // Invoking myMethod() using my_ptr 

    int a = 5;
    int *p = (*my_ptr)(&a); 
    printf("Bye %d\n", *p);

    return 0; 
} 

I thought my syntax for a function pointer, my_ptr, would be correct where it could take an int pointer as it's parameter and return an int pointer but when I compile it, I get the error that:

 error: function 'my_ptr' is initialized like a variable
 int *my_ptr(int *) = myMethod; 

Could someone explain the error/issue? Thanks!

Anna
  • 379
  • 5
  • 16

3 Answers3

1

int* my_ptr(int*) is the prototype of a function. You want a function pointer: int* (*my_ptr)(int*)

Nelfeal
  • 12,593
  • 1
  • 20
  • 39
1

Change pointer to function myMethod to this:

int *(*my_ptr)(int *) = &myMethod;
0

You should use int *(*my_ptr)(int *) = myMethod; not int *my_ptr(int *) = myMethod;

The following code could work:

#include <stdio.h>

int *myMethod(int *a)
{
   printf("Hello");
   return a;
}

int main()
{
    int *(*my_ptr)(int *) = myMethod;

    int a = 5;
    int *p = (*my_ptr)(&a);
    printf("Bye %d\n", *p);

    return 0;
}
Yunbin Liu
  • 1,484
  • 2
  • 11
  • 20