Functions returning Pointers

The C language allows a function to return a pointer. Since pointers are a data type in C, so we can force a function to return a pointer to the calling function.

Now to do this we have to declare a function in a way that it returns a pointer. Following is the declaration syntax for function returning pointer :
 returnType *functionName(param list);
Where :
  • returnType is the type of the pointer that will be returned by the function functionName.
  • param list is the list of the parameters of the function which is optional.

For example :
int *MyFunc() {
  // function statement
}
Now lets see an example c code :
#include <stdio.h>

int *Max(int *, int *);

int main() {
  int x = 10;
  int y = 20;

  int *ptr = Max(&x, &y);
  printf("%d\n", *ptr);
  return 0;
}

int *Max(int *a, int *b) {
  if(*a > *b) {
    return a;
  } else {
    return b;
  }
}
Output :

20

At above code the function Max() will returns the bigger number out of two given numbers. In the main function the Max() is called with the address of two number x and y, and the returned value is stored on the integer pointer ptr.
 int *ptr = Max(&x, &y);
The function max()  takes two pointer arguments, compare them and returns the address of the bigger number.

Also note that the address returned must be the address of a variable in the calling function, because returning a pointer to a local variable from the called function would cause serious errors. Otherwise the programmer would have to define the local variable as static variable in the called function. For example :
#include <stdio.h>

int *Multiply(int, int);

int main() {
  int x = 10;
  int y = 20;

  int *ptr = Multiply(x, y);
  printf("%d\n", *ptr);
  return 0;
}

int *Multiply(int a, int b) {
  static int ans;
  ans = a*b;
  return &ans;
}
Output :

200

At above example, inside Multiply() function, the integer variable ans is declared as static variable.

Next Topic :