Sunday, August 28, 2011

Examples of Function pointer







#include
int * function();
int main(){
	auto int *x;
	int *(*ptr)();
	ptr=&function;
	x=(*ptr)();
	printf("%d",*x);
	getchar();getchar();
	return 0;
}
int *function(){
	static int a=10;
	return &a;
}
//Output: 10
/*Explanation: Here function is function whose parameter is void data type
and return type is pointer to int data type.
x=(*ptr)()
=> x=(*&functyion)() //ptr=&function
=> x=function() //From rule *&p=p
=> x=&a
So, *x = *&a = a =10*/
#include
int find(char);
int(*function())(char);
int main(){
	int x;
	int(*ptr)(char);
	ptr=function();
	x=(*ptr)('A');
	printf("%d",x);
	getchar();getchar();
	return 0;
}
int find(char c){
	return c;
}
int(*function())(char){
	return find;
}
//output: 65
/* Explanation:
x=(*ptr)(‘A’)
=> x= (*function ()) (‘A’) //ptr=function ()
//&find=function () i.e. return type of function ()
=> x= (* &find) (‘A’)
=> x= find (‘A’) //From rule*&p=p
=> x= 65*/
#include
char * call(int *,float *);
int main(){
	char *string;
	int a=2;
	float b=2.0l;
	char *(*ptr)(int*,float *);
	ptr=&call;
	string=(*ptr)(&a,&b);
	printf("%s",string);
	getchar();getchar();
	return 0;
}
char *call(int *i,float *j){
	static char *str="c-pointer.blogspot.com";
	printf("%s\n",str);
	str=str+*i+(int)(*j);
	return str;
}
//output: inter.blogspot.com
/*str= str+*i+ (int) (*j)
=”c-pointer.blogspot.com” + *&a+ (int) (*&b)
//i=&a, j=&b
=”c-pointer.blogspot.com” + a+ (int) (b)
=”c-pointer.blogspot.com” +2 + (int) (2.0)
=”c-pointer.blogspot.com” +4
=”inter.blogspot.com”*/

No comments:

Post a Comment