Sunday, August 28, 2011

How to Use Arrays of Function Pointers







#include
//2.8 How to Use Arrays of Function Pointers
int DoMore(float a,char b,char c){printf("DoMore\n");return int(a-b+c);}
int Dolt(float a,char b,char c){printf("Dolt\n");return int(a+b+c);}
// type-definition: 'pt2Function' now can be used as type
typedef int (*pt2Function)(float, char, char);
// illustrate how to work with an array of function pointers
void Array_Of_Function_Pointers(){
	printf("\nExecuting Array_Of_Function_Pointers\n");
	// 1st way using the typedef
	pt2Function funcArr1[10] = {NULL};
	// 2nd way directly defining the array
	int (*funcArr2[10])(float, char, char) = {NULL};
	funcArr1[1] = funcArr2[0] = &DoMore;
	funcArr1[0] = funcArr2[1] = &Dolt;
	// calling a function using an index to address the function pointer
	printf("%d\n", funcArr1[1](12, 'a', 'b')); // short form
	printf("%d\n", (*funcArr1[0])(12, 'a', 'b')); // "correct" way of calling
	printf("%d\n", (*funcArr2[1])(56, 'a', 'b'));
	printf("%d\n", (*funcArr2[0])(34, 'a', 'b'));
}
int main(){
	Array_Of_Function_Pointers();
	getchar();getchar();
	return 0;
}

No comments:

Post a Comment