| Previous | Home | Next |
The function pointer is a powerful feature in c. In memory a function has a physical location that can be assigned to a pointer. This address is the entry point of the function and it is the address used when the function is called. Once a pointer points to a function, the function can be called through that pointer. Function pointers also allow functions to be passed as arguments to other functions or function pointers is a pointers, that point to the address of a function.
Now we can se that when we run the any program than that running program gets a certain space in the main-memory. than the executable compiled program code and variables are put inside this memory. Thus that program code have a functions than that function in the program code is, like e.g. a character field, nothing else than an address. It is only important how you, or better your compiler/processor, interpret the memory a pointer points to.
# Passing pointers to functions in C
#include <stdio.h>
/* function declaration */
double calAverage(int *ary, int sz);
int main ()
{
/* an int array with 5 elements */
int price[5] = {1000, 2, 3, 17, 50};
double ag;
/* pass pointer to the array as an argument */
ag = calAverage( price, 5 ) ;
/* output the returned value */
printf("Average value is: %f\n", ag );
return 0;
}
double calAverage(int *ary, int sz)
{
int i, sum = 0;
double ag;
for (i = 0; i < sz; ++i)
{
sum += ary[i];
}
ag = (double)sum / sz;
return ag;
}
Average value is: 214.400000
| Previous | Home | Next |