Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

This is my program in 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?

like image 810
Tommz Avatar asked Mar 09 '26 14:03

Tommz


1 Answers

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 &)

like image 75
Pubby Avatar answered Mar 11 '26 05:03

Pubby



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!