Monday, 20 February 2012

Explain the variable assignment in the declaration int *(*p[10])(char *, char *); | C Programming

It is an array of function pointers that returns an integer pointer. Each function has two arguments which in turn are pointers to character type variable. p[0], p[1],....., p[9] are function pointers.
return type : integer pointer.
p[10] : array of function pointers
char * : arguments passed to the function
Program: Example program to explain function pointers.
#include<stdio.h>
#include<stdlib.h>
int *(*p[10])(char *, char *);
//average function which returns pointer to integer whose value is average of ascii value of characters passed by pointers
int *average(char *, char *);
//function which returns pointer to integer whose value is sum of ascii value of characters passed by pointers
int *sum(char *, char *);
int retrn;
int main(void) 
{
int i;
for (i = 0; i < 5; i++) 
{
//p[0] to p[4] are pointers to average function.
p[i] = &(average);
}
for (i = 5; i < 10; i++) 
{
//p[5] to p[9] are pointers to sum function
p[i] = &(sum);
}
char str[10] = "nodalo.com";
int *intstr[10];
for (i = 0; i < 9; i++)
 {
//upto p[4] average function is called, from p[5] sum is called.
intstr[i] = p[i](&str[i], &str[i + 1]);
if (i < 5) {
//prints the average of ascii of both characters
printf(" \n average of %c and %c is %d",
str[i], str[i + 1],*intstr[i]);
}
else 
{
//prints the sum of ascii of both characters.
printf(" \n sum of %c and %c is %d",
str[i], str[i + 1], *intstr[i]);
}
}
return 0;
}/
/function average is defined here
int *average(char *arg1, char *arg2)
 {
retrn = (*arg1 + *arg2) / 2;
return (&retrn);
}
//function sum is defined here
int *sum(char *arg1, char *arg2) 
{
retrn = (*arg1 + *arg2);
return (&retrn);
}
Output:
average of n and o is 110
average of o and d is 105
average of d and a is 98 average of d and a is 98
average of a and l is 102
average of l and o is 109
sum of o and . is 157
sum of . and c is 145
sum of c and o is 210
sum of o and m is 220
Explanation:
In this program p[10] is an array of function pointers. First five elements of p[10] point to the function: int *average(char *arg1,char *arg2). Next five elements point to the function int *sum(char *arg1,char *arg2). They return pointer to an integer and accept pointer to char as arguments.
Function average:
int *average(char *arg1,char *arg2) This function finds the average of the two values of the addresses passed to it as arguments and returns address of the average value as an integer pointer.
Function sum:
int *sum(char *arg1,char *arg2) This function finds the sum of the two values of the addresses passed to it as arguments and returns address of the sum value as an integer pointer.