简体   繁体   English

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

[英]How to print string from function which returns pointer on that string in C?

This is my program in C: 这是我在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;
}
  • *with this i'm trying to print what is returning from pointer but it seems like not working. *这个我试图打印从指针返回的东西,但它似乎无法正常工作。

What am I doing wrong? 我究竟做错了什么?

You need to call the function pointers, ie use parenthesis: 你需要调用函数指针,即使用括号:

#include <stdio.h>

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

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


printf ("%s\n", pointer());
//              ^^^^^^^^^
return 0;
}

* isn't needed for function pointers. 函数指针不需要* (neither is & ) (都不是&

You call a function through a pointer in the same exact way that you call a function directly, as if that pointer was function's name: 您通过指针调用函数的方式与您直接调用函数的方式相同,就好像该指针是函数的名称一样:

printf ("%s\n", pointer());

Starting with the ANSI C standard, the asterisks and ampersands around function pointers are optional. 从ANSI C标准开始,函数指针周围的星号和&符号是可选的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM