C 打印功能地址

C 打印功能地址,c,function,pointers,function-pointers,C,Function,Pointers,Function Pointers,我一直在尝试一种方法来找出如何打印函数的地址,这就是我想到的 #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

我一直在尝试一种方法来找出如何打印函数的地址,这就是我想到的

#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;
}

我的问题是,使用%p格式说明符是打印函数地址的正确方法还是有其他方法?

如果不使用单独的指针打印函数地址,可以在
printf
中使用函数名

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

要以十六进制格式打印地址,可以使用
%p

这是不正确的<代码>%p仅适用于对象指针类型(事实上,
void*
)。函数指针没有格式说明符。

函数的名称就是它的地址。通过使用:
printf(“函数地址:%p\n”,test),可以获得相同的结果
和yes:%p是打印指针值(内存地址)的正确格式说明符,因为实现知道指针的外观。@mcleod_ideafix:这是不正确的<代码>%p可以与
void*
指针一起使用,也可以(转换后)与其他对象指针一起使用<代码>%p不能与函数指针一起使用。我刚刚在Linux和gcc上测试了它。使用-Wall编译不会触发任何警告,它会打印main的实际地址。使用
-pedantic errors
编译时,此操作失败,消息
格式指定类型为“void*”,但参数的类型为“void(*)()”
 printf("The address of the function is =%p\n",test);