7

I've been trying a way to figure out how to print the address of the function, This is what I came up with

#include<stdio.h>
int test(int a, int b)
{
     return a+b;
}
int main(void)
{
     int (*ptr)(int,int);
     ptr=&test;
     printf("The address of the function is =%p\n",ptr);
     printf("The address of the function pointer is =%p\n",&ptr);
     return 0;
}

It o/p something like this without any warning and errors

address of function is =0x4006fa
address of function pointer  is =0x7fffae4f73d8

My question whether using %p format specifier is the correct way to print the address of the function or is there any other way to do so?

  • 2
    The name of the function is the address of it. You can achieve the same result by using: `printf ("Address of function: %p\n", test);` And yes: %p is the correct format specifier to print pointer values (memory addresses) because the implementation knows how your pointers look like. – mcleod_ideafix Mar 23 '15 at 05:04
  • 1
    @mcleod_ideafix: That's is incorrect. `%p` can be used with `void *` pointers and (after conversion) with other object pointers. `%p` cannot be used with function pointers. – AnT stands with Russia Mar 23 '15 at 05:11
  • I've just tested it on Linux and gcc. Compiling with -Wall doesn't trigger any warnings, and it prints the actual address of main – mcleod_ideafix Mar 23 '15 at 12:13

2 Answers2

9

This is not correct. %p is only for object pointer types (in fact, void * specifically). There is no format specifier for a function pointer.

M.M
  • 138,810
  • 21
  • 208
  • 365
1

Without using the separate pointer for print the address of the function, You can use the name of the function in the printf.

 printf("The address of the function is =%p\n",test);

For printing the address in the hexa-decimal format you can use the %p.

sharon
  • 734
  • 6
  • 15
  • 1
    This fails when compiling with `-pedantic-errors`, with the message `format specifies type 'void *' but the argument has type 'void (*)()'` – Rafael Eyng Jan 30 '20 at 17:15