4

I am having hard time understanding function pointers and the syntax associated with it. I looked online and read a bit and I all could understand are simple scenarios. I am not able to extend it.

What I understand is below scenario wherein a function's address is passed to a pointer and we use it for future reference.

int GetSomething(char *);
typedef int (*pGetSomething)(char *);

int main(void)
{
    char * what = "I atleast got this";
    pGetSomething pfGetSomething;
    pfGetSomething = &GetSomething;
    pfGetSomething(what);  
    return 0;
}

int GetSomething(char *format)
{
    printf("%s \n \n ", format);
    return 0;
}

Now Lets say I want to extend this further such that -

PGetSomething calls a Void function and returns me address to a function which has argument of char* and return type int.

I tried below syntax and tried to return a pointer to GetSomething. But I guess I am clueless how to approach. All I could muster was below syntax. Can someone help me understand what would be required to achieve something like as mentioned with a code snippet if possible ?

typedef int (*pGetSomething(void))(char *);
m.s.
  • 16,063
  • 7
  • 53
  • 88
oneday
  • 629
  • 1
  • 9
  • 32
  • A more sound scenario is when you need a function to be apart of a struct. I have used these in creating generic stacks, queue, deques in pure C for freeing allocated memory. I will find some documentation for you in regards to your questions. – fingaz Aug 10 '15 at 01:57
  • 1
    Here's everything you need: [](http://stackoverflow.com/questions/840501/how-do-function-pointers-in-c-work) – fingaz Aug 10 '15 at 02:00
  • Thank you going through the link did help - able to perform the operation I was looking for. – oneday Aug 10 '15 at 02:55
  • 1
    Please do not edit a solution into your Question. Instead, accept a posted answer. If there is no good posted answer then you may post an answer to your own question – M.M Aug 10 '15 at 03:51
  • In the scenario you give, the function's address is not passed to a pointer. It is assigned to the pointer. When you say you "tried to return a pointer to GetSomething", that implies that you tried to call a function which returns the address of GetSomething, but I don't think that is what you are trying to do. Also, "PGetSomething calls a Void function and returns me address to a function" makes little sense. You can invoke a function through PGetSomething, and that function could return the address of another function....but I don't know if that's what you mean. – William Pursell Aug 10 '15 at 04:16

0 Answers0