pointers and function arguments

Pointer in function parameter list is used to hold address of argument passed during function call. This is also known as call by reference. When a function is called by reference any change made to the reference variable will effect the original variable.

Example: Sorting an array using Pointer

#include <stdio.h>
#include <conio.h>
void sorting(int *x, int y);
void main()
{
 int a[5],b,c;
 clrscr();
 printf("enter 5 nos");
 for(b=0; b<5; b++)
 {
  scanf("%d",&a[b]);
 }
 sorting(a, 5);
 getch();
}

void sorting(int *x, int y)
{
 int i,j,temp;
 for(i=1; i<=y-1; i++)
 {
  for(j=0; j*(x+j+1))
   {
    temp=*(x+j);
    *(x+j)=*(x+j+1);
    *(x+j+1)=temp;
   }
  }
 }
 for(i=0; i<5; i++)
 {
  printf("\t%d",*(x+i));
 }
}

Function returning Pointer

A function can also return a pointer to the calling function. In this case you must be careful, because local variables of function doesn't live outside the function, hence if you return a pointer connected to a local variable, that pointer be will pointing to nothing when function ends.
#include <stdio.h>
#include <conio.h>
int* larger(int*, int*);
void main()
{
 int a=15;
 int b=92;
 int *p;
 p=larger(&a, &b);
 printf("%d is larger",*p);
}

int* larger(int *x, int *y)
{
 if(*x > *y)
  return x;
 else
  return y;
}

Safe ways to return a valid Pointer.

  1. Either use argument with functions. Because argument passed to the functions are declared inside the calling function, hence they will live outside the function called.

  2. Or, use static local variables inside the function and return it. As static variables have a lifetime until main() exits, they will be available througout the program.

Pointer to functions

It is possible to declare a pointer pointing to a function which can then be used as an argument in another function. A pointer to a function is declared as follows,
type (*pointer-name)(parameter);

Example :
int (*sum)();   //legal declaraction of pointer to function
int *sum();   //This is not a declaraction of pointer to function 
A function pointer can point to a specific function when it is assigned the name of the function.
int sum(int, int);
int (*s)(int, int);
s = sum;
s is a pointer to a function sum. Now sum can be called using function pointer s with the list of parameter.
s (10, 20);

Example of Pointer to Function

#include <stdio.h>
#include <conio.h>

int sum(int x, int y)
{
 return x+y;
}

int main( )
{
 int (*fp)(int, int);
 fp = sum;
 int s = fp(10, 15);
 printf("Sum is %d",s);
 getch();
 return 0;
}
Output : 25

Complicated Function Pointer Example

You will find a lot of complex function pointer examples around, lets see one such example and try to understand it.
void *(*foo) (int*) ;
It appears complex but it is very simple. In this case (*foo) is a pointer to the function, whose return type isvoid* and argument is of int* type.

No comments:

Post a Comment