使用指针打印功能地址 [英] Printing address of function by using pointer
问题描述
我正在尝试使用下面代码中所示的 printf
语句两次打印函数指针地址...
I am trying to print a function pointer address two times using a printf
statement shown in below code...
class B
{
public:
int fun()
{
}
};
int main()
{
int (B::*pb)()=&B::fun;
printf("ptr:%x | %x\n",pb,pb); //Output is ptr:8048730 | 0
}
当我将同一变量传递给 printf
它应该打印相同的值,但是得到结果后,我感到很惊讶。
when i am passing same variable to printf
it should print the same value but after getting the result i am surprised.
任何人都可以解释这个原因或我做错了什么地方。
Can anyone explain the reason for this or somewhere i am doing wrong.
gcc版本4.8.2(GCC)
推荐答案
如果打开警告(将 -Wall
标志传递给编译器),编译器将告诉您您在做什么。错误:
If you turn on the warnings (pass the -Wall
flag to the compiler), the compiler will tell you what you are doing wrong:
warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int (B::*)()’ [-Wformat]
warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 3 has type ‘int (B::*)()’ [-Wformat]
通常,我只能鼓励您打开警告。
In general, I can only encourage you to turn on warnings.
现在有以下情况(未定义的行为):
Now a hack (undefined behavior) is the following:
std :: printf( ptr:% p |%p\n,(void *)funcptr,(void *)funcptr);
这仍然给出以下警告:
警告:从'int转换(B :: *)()'到'void *'[-Wpmf-conversions]
,但是程序会打印两次相同的地址如您所愿。仍然是未定义的行为,请参见如何格式化函数指针?通过遵循公认的答案(从那里被无耻地偷走的代码) ,则可以按以下方式打印地址:
but the program prints the same address twice as you wished. It is still undefined behavior, see How to format a function pointer? By following the accepted answer (code shamelessly stolen from there), one could print the address as follows:
#include <cstdio>
class B {
public:
int fun() { return 0; }
};
int main()
{
int (B::*funcptr)()=&B::fun;
unsigned char *p = (unsigned char *)&funcptr;
for (unsigned int i = 0; i < sizeof funcptr; ++i)
{
std::printf("%02x ", p[i]);
}
std::putchar('\n');
return 0;
}
根据该答案,这是实现此目的的唯一合法方法。它不会发出任何警告。
According to that answer it is the only legal way to achieve this. It doesn't give any warning.
这篇关于使用指针打印功能地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!