Advertisment

Let's C pointers and functions

author-image
CIOL Bureau
Updated On
New Update

We now know enough about functions and pointers per se, now let's take a look at how the two can be used

together to write more efficient code. If we had to pass an array to a function, only the address of the array

i.e. the first element is passed and not all the elements of the array. Once the address is passed,

the function can use it to access and manipulate the elements of the array. In a similar manner, the address

of a variable can also be passed to a function using the ‘address of’ operator &, this method of calling

a function by passing the address of a variable is known as

call by reference. Whereas the method of calling a function by passing the actual value of variables is known as

call by value. The variable in the function receiving the address should also be declared as a pointer. The function that receives the address of the variable can change the value of the variable used in the call. For example:



 main()


 {


   int x;


   void change();


   x=20;


   change(&x);


   printf(" \ nNew value of x = %d",x);


 }





void change(ptr)


 int *ptr;


 {


   *ptr=30;


 }


Output: New value of x = 30















Pointers to functions



Just like a variable, a function too has an address location in memory, hence it is possible to declare
a pointer to a function, which can in turn be used as an argument in another function. The declaration

is as follows:



 datatype (*ptr)();



This tells the compiler that ptr is a pointer to a function which returns a value of type datatype.

Note: The parentheses around *ptr are necessary



 datatype *ptr();



would declare ptr as a function that returns a pointer of type datatype. A function pointer can be

made to point to a function by simply assigning the name of the function to the pointer. For example:



 int (*ptr)(), add();


 ptr=add;



This declares ptr as a function pointer and add as a function. Then the pointer ptr is made to point

to the function add in the following assignment statement. Now to call the function add:



 (*ptr)();





/* Program to illustrate the use of pointers to structures */


 main()


 {


   int a, b, c;


   int (*pmul)(), mul();


   void (*read)(), (*write)(), input(), output();


   read=input; /* Initialization */


   pmul=mul;


   write=output;


   (*read)( &a,&b);


   c=(*mul)(a,b);


   (*write)(a,b,c);


 }





 void input(int *x,int *y)


 {


   printf(" \nEnter the two values : ");


   scanf("%d %d",x,y);


 }





 mul(int m, int n)


 {


   int p;


   p= m*n;


   return(p);


 }





 void output(int r, int t,int s)


 {


   printf(" \nThe values entered were : %d and %d",r,t);


   printf("\nThe product of the two = %d",s);


 }


Input:


Enter the two values : 10 20


Output:


The values entered were : 10 20


The product of the two = 200











































tech-news