如何从C中返回指针的函数打印字符串?

Tom*_*mmz 3 c function-pointers

这是我在C中的程序:

#include <stdio.h>

char const* voice(void){
  return "hey!";
}

int main(){
const char* (*pointer)(void);
pointer = &voice;


printf ("%s\n", *pointer); // check down *
return 0;
}
Run Code Online (Sandbox Code Playgroud)
  • *这个我试图打印从指针返回的东西,但它似乎无法正常工作.

我究竟做错了什么?

Pub*_*bby 6

你需要调用函数指针,即使用括号:

#include <stdio.h>

char const* voice(void){
  return "hey!";
}

int main(){
const char* (*pointer)(void);
pointer = &voice;


printf ("%s\n", pointer());
//              ^^^^^^^^^
return 0;
}
Run Code Online (Sandbox Code Playgroud)

*函数指针不需要.(都不是&)