3

I have a pointer to a function returning a const char pointer. My question is how to print the pointer and then also the object (the string itself) referenced by the pointer(s).

Here is the code:

#include <stdio.h>

char const *func(void)
{
    printf("Printed func string.\n");
    return "Pointed func string.\n";
}

int main(void) {
    char const *(*fp)(void) = func;

    /*print statements here*/

    return 0;
}

I get either a ISO C forbids conversion of function pointer to object pointer type or some undefined behavior.

EDIT:

int main(void) {
    char const *(*fp)(void) = func;

    unsigned char *p = (unsigned char *)&fp;
    /*print statements here*/
    printf("The: %p\n",(char *) p);


    return 0;
}

OUTPUT: 0x7fff36753500

Is not correct.

Dimitar
  • 4,402
  • 4
  • 31
  • 47

1 Answers1

4
char const *(*fp)(void) = func;

Here, you are only assigning func to the function pointer. You need to call it to get the string returned by the function.

   char const *(*fp)(void) = func;

   const char *p = fp();
   printf("In main: %s", p);

That's how you print the string. There's no standard format specifier to print a function pointer. %p is only for data pointer, not for a function pointer. So to print a function pointer using %p is undefined behaviour.

If you really need to print the function pointer, then convert it to a character pointer and print them:

   unsigned char *cp = (unsigned char*)&fp;

   for(i=0;i<sizeof fp; i++) {
      printf("[%08x]", cp[i]);
   }

This works because converting any object to a character pointer is allowed (char*, unsigned char* or signed char*). What it prints is in a implementation-defined format (just like %p).

P.P
  • 117,907
  • 20
  • 175
  • 238
  • This "*then convert it to a character pointer*" is misleading. As your code does something different. – alk Dec 13 '15 at 13:12