dim*_*im8 3 c pointers function-pointers function
我有一个指向返回 const char 指针的函数的指针。我的问题是如何打印指针,然后打印指针引用的对象(字符串本身)。
这是代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
我得到一个ISO C forbids conversion of function pointer to object pointer type
或一些未定义的行为。
编辑:
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;
}
Run Code Online (Sandbox Code Playgroud)
输出:0x7fff36753500
是不正确的。
char const *(*fp)(void) = func;
Run Code Online (Sandbox Code Playgroud)
在这里,您仅分配func
给函数指针。您需要调用它来获取函数返回的字符串。
char const *(*fp)(void) = func;
const char *p = fp();
printf("In main: %s", p);
Run Code Online (Sandbox Code Playgroud)
这就是打印字符串的方式。没有标准格式说明符来打印函数指针。%p
仅适用于数据指针,不适用于函数指针。因此使用打印函数指针%p
是未定义的行为。
如果您确实需要打印函数指针,请将其转换为字符指针并打印它们:
unsigned char *cp = (unsigned char*)&fp;
for(i=0;i<sizeof fp; i++) {
printf("[%08x]", cp[i]);
}
Run Code Online (Sandbox Code Playgroud)
这是可行的,因为允许将任何对象转换为字符指针(char*
、unsigned char*
或signed char*
)。它打印的内容采用实现定义的格式(就像%p
)。