I am currently experimenting with function pointers as part of a larger project. Drawing from both online sources and textbooks.

The problem however is that after storing the values as an array, when i call them the functions either fail to be called, or if i attempt to print the return value from the function i end up simply printing the memory address(no matter how i alter the pointing). Probably missing a fairly un-subtle error but... i can't see it.

compiler:
GCC with -ansi flag

implementation 1:

void caller(int name){ 
int (*f[NUMBEROFFUNC])(void)= { &aR1, &aR2, &aR3};
printf("%d\n", (*f[name]));     /*statement to print return value*/
}

implementation 2:

typedef int (*funcptr)(void);

void caller(int name){ 

funcptr *funcarr[NUMBEROFFUNC] = {NULL}; /*position in array is pointer to data*/

funcarr[0]= &aR1;	
funcarr[1]= &aR2;	
funcarr[2]= &aR3;	

printf("%d\n", (*funcarr[name]));      /*statement to print return value*/

}

Any assistance is greatly appreciated.

Recommended Answers

All 5 Replies

Don't forget the argument list when you call the function through a function pointer:

#include <stdio.h>

int foo ( void )
{
  return 12345;
}

int main ( void )
{
  int (*p)( void ) = &foo;

  printf ( "%d\n", (*p)() );

  return 0;
}

<< int (*p)( void ) = &foo;

'foo' by itself is the address of the fn.
so
int (*p)( void ) = foo;
will be enough, if I am right.

>'foo' by itself is the address of the fn.
You can do two things with a function: call it and take its address. Both foo and &foo do exactly the same thing, but I prefer the latter because it's more obvious that I'm looking for an address.

You can also omit the pointer junk from the actual call:

printf ( "%d\n", p() );

But I generally keep it for the same reason, it's more obvious what's going on.

Thanks, now I understand why calling (*main)() worked for me sometimes back

Thank you very much, the missing parentheses fixed the problem.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.