如何格式化函数指针? [英] How to format a function pointer?
问题描述
有没有什么办法来打印一个指向ANSI C函数?当然,这意味着你必须强制转换函数指针指向void,但现在看来这是不可能的?
的#include<&stdio.h中GT;诠释主(){
INT(* funcptr)()=主; 的printf(%P \\ N(无效*)funcptr);
的printf(%P \\ N(无效*)主); 返回0;
}
$ GCC -ansi -pedantic -Wall -o test.c的
测试
test.c的:在功能
'主':
test.c的:6:警告:ISO C
禁止函数指针转换
为一个对象指针
test.c以7:
警告:ISO C禁止转换
函数指针对象的指针
键入
$ ./test
0x400518
0x400518
块引用>这是工作,但非标准...
解决方案要做到这一点的唯一合法途径是访问补课使用字符类型的指针字节。像这样的:
的#include<&stdio.h中GT;诠释主(){
INT(* funcptr)()=主;
无符号的char * p =(无符号字符*)及funcptr;
为size_t我; 对于(i = 0; I< sizeof的funcptr;我++)
{
的printf(%02X,P [I]);
}
的putchar('\\ n'); 返回0;
}双关语的函数指针作为
无效*
,或任何非字符类型,如<一个href=\"http://stackoverflow.com/questions/2741683/how-to-format-a-function-pointer/2741694#2741694\">dreamlax's答案确实,是不确定的行为。这是什么组成的函数指针字节实际上的意思是的是实现相关。他们可能只是重新present的索引功能的表格,例如。
Is there any way to print a pointer to a function in ANSI C? Of course this means you have to cast the function pointer to void pointer, but it appears that's not possible??
#include <stdio.h> int main() { int (*funcptr)() = main; printf("%p\n", (void* )funcptr); printf("%p\n", (void* )main); return 0; }
$ gcc -ansi -pedantic -Wall test.c -o test
test.c: In function 'main':
test.c:6: warning: ISO C forbids conversion of function pointer to object pointer type
test.c:7: warning: ISO C forbids conversion of function pointer to object pointer type
$ ./test
0x400518
0x400518It's "working", but non-standard...
解决方案The only legal way to do this is to access the bytes making up the pointer using a character type. Like this:
#include <stdio.h> int main() { int (*funcptr)() = main; unsigned char *p = (unsigned char *)&funcptr; size_t i; for (i = 0; i < sizeof funcptr; i++) { printf("%02x ", p[i]); } putchar('\n'); return 0; }
Punning the function pointer as a
void *
, or any non character type, as dreamlax's answer does, is undefined behaviour.What those bytes making up the function pointer actually mean is implementation-dependent. They could just represent an index into a table of functions, for example.
这篇关于如何格式化函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!