Help with pointers to functions

I'm trying to wrap my brain around pointers to functions. In the following code, I'm having dereferencing issues with '*z' at line 21. What am I missing?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

float funcFloat ( char c ) {
	float f = 3.14 + c;
	return f;
}

void* funcInt ( int anyInt ) {
	float ( * fp )( char );
	fp = funcFloat;
	return fp;
}

int main() {
	  void* ( *fp )( int ) = funcInt;
	  char x = 'x';
	  int q = 3;
	  void* z = (*fp)(q);
	  float j = (*z)(x);
	  cout << j;
	  system("PAUSE");
	  return 0;
} 
Last edited on
In this statements

1
2
	  void* z = (*fp)(q);
	  float j = (*z)(x);


z has type void *. It is not a pointer to a function. And you may not dereference a void pointer, because void is an incomplete type.

You could write

float j = static_cast<float ( * )( char )>( z )( x );
or
float j = reinterpret_cast<float ( * )( char )>( z )( x );
Last edited on
So if I change funcInt to a float*, I'm still getting errors. In line 12, it says fp is an invalid type. I would think that fp in funcInt is a pointer to a float pointer:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

float funcFloat ( char c ) {
	float f = 3.14 + c;
	return f;
}

float* funcInt ( int anyInt ) {
	float ( * fp )( char );
	fp = funcFloat;
	return fp;
}

int main() {
	  float* ( *fp )( int ) = funcInt;
	  int q = 3;
	  char x = 'x';
	  float* z = (*fp)(q);
	  float j = (*z)(x);
	  cout << j;
	  system("PAUSE");
	  return 0;
} 
I showed you how it shall be done.
That makes sense. Thank you!
Topic archived. No new replies allowed.