Pointers and Functions
Pointer to function
Contains address of functionSimilar to how array name is the address of the first elementFunction name is the starting address of the code that defines a function
Function pointers can be
Passed to functionsStored in arraysAssigned to other function pointers
Pointers can be passed as arguments to a function definition.
Passing pointers to a function is called, “call by reference”.
In “call by reference”, whatever changes are made to the formal arguments will effected in the actual arguments in the calling function.
In a “call by reference” the actual arguments must be pointers or references (address).
Pointer arguments are useful in functions, because they allow accessing the original data in the calling program.
Function pointers are pointers, which point to the address of a function.
Declaration:
<return type> (*function_pointer) (type1 arg1, type2 arg2, .....);
Example:
int calculate1 (float a, char b, char c)
{printf(“Calculate1\n”);return a+b+c;}
Example:
C program to find sum and difference of two numbers
#include<stdio.h>/*Definition of add function */int add(int a, int b){return(a+b);}/* Definition of sub function */int sub(int a, int b){return(a-b);}int (*fp)(int, int); //function pointer/* fp points to a function as opposed to a value */int main(){fp=add; //fp is dynamically assigned a function ‘add’printf(“Sum = %d\n”, fp(4,5)); //Equivalent to calling add(4,5)fp=sub;printf(“Difference =a %d\n”,fp(6,2));}
OUTPUT
Sum =9Difference = 4
Example:
An example of a C program where we pass an unsigned long pointer to a function and change the value inside the function. It reflects back in the calling function.
#include<stdio.h>
#include<conio.h>
void getSeconds(unsigned long *par);
int main()
{
unsigned long awx;
getSeconds(&sec); //Passing the address of sec. This is ‘pass by reference’.
/* Print the actual value*/
printf(“Number of seconds %d\n”,sec);
return 0;
}
void getSeconds(unsigned long *par)
{
/* get the current number of seconds */
*par = time(NULL); //the value of actual argument is modified. Here, it is sec.
return;
}
OUTPUT
Number of seconds: 1392050354
Example:
The function, which can accept a pointer, can also accept an array as shown in the below example
#include<stdio.h>
/*function declaration*/
double getAverage(int *arr, int size);
int main()
{
/*Declaring and initializing an int array with 5 elements*/
int balance[5]={1000,2,3,17,50};
double avg;
/*pass pointer to the array as an argument */
avg=getAverage(balance, 5); /*passing an array of integers. The formal parameters is a pointer to integer*/
/*output the returned value*/
print(“Average value is :%f\n”,avg);
return 0;
}
double getAverage(int *arr, int size) //this accepts an array of integers as an argument
{
int i, sum=0;
double avg;
for(i=0; i<sze; ++)
{
sum +=arr[i];
}
avg=(double)sum / size;
return avg;
}
OUTPUT
Average value is: 214.400000
Social Plugin