3

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?

1
  • I guess you want to keep the function pointer stuff, so just call the function instead of dereferencing; printf( "%s\n", pointer( ) ); Commented Apr 2, 2013 at 1:34

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. Yea, I was asking myself why pointer = voice; is working as well.
4

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.

1 Comment

The alternative notation is (*pointer)(), with parentheses and an asterisk. *pointer() is valid but returns the first character of the string returned by the function pointer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.