Tommz
Tommz

Reputation: 3453

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;
}

What am I doing wrong?

Upvotes: 3

Views: 625

Answers (2)

Pubby
Pubby

Reputation: 53097

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

Upvotes: 6

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727077

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.

Upvotes: 4

Related Questions