POINTERS AND FUNCTIONS:


POINTERS AND FUNCTIONS:

Every variable in ’C’ has an address except register variable. We can access these addresses using pointers. Likewise, functions in ‘C’ also have addresses. The address of a function can be known by pointers to function.

A pointer to a function can be declared as follows.

            Data type (*function name)(parameter list);
Eg:-
            int (*p)( );

            It indicates ‘p’ is a pointer to a function which stores address of a function.

Ƙ  A Program to call a function using pointers.


#include<stdio.h>
#include<conio.h>
void (*p)( );
void show( );
void main( )
{
p=show;
           (*p)( );
       }
       void show
       {
printf(“address of function%u”,show);
        }



Functions returning pointers:

                        The way in which a function can return an integer, float or any other datatype, it can also return a pointer, it has to be mentioned explicitly.
            A function returning a pointer can be declared as follows:-
                                    Data type *function name(parameters);
Eg:-

            int *fun();
            void main()
{
            int *p;
            p=fun();
printf(“%u”,p);
}
int *fun()
{
int a=5;
printf(“address of a is”);
return(&a);
}

Here, the declaration int *fun(): indicates that fun() is a function without parameters but return an integer pointer.

Functions returning multiple values:-

            Normally a function can return only one value at a time. But it is possible to make a function return multiple values at a time by using pointers.
Eg:-
#include<stdio.h>
 #include<conio.h>
int fun(int *, int *, int *, int *);
void main()
{
int x,y, sum, diff;
clrscr();
printf(“\n enter any 2 values”);
scanf(“%d%d”,&x,&y);
fun(&x, &y, &sum, &diff);
printf(“sum=%d”,sum);
printf(“diff=%d”,diff);
}
int fun(int *a, int *b, int *c, int *d);
{
            *c=*a+*b;
            *d=*a-*b;
}





No comments:

Post a Comment