C Tutorial C References

C - Return Pointer from Function



A pointer is a variable which stores address of another variable. C allows to pass pointers to the function as well as return a pointer from a function. This can be achieved by declaring the return type of the function as a pointer. See the syntax below:

Syntax

ponter_return_type function_name(parameters) {
  statements;
}

//for example
int * MyFunction() {
  statements;
}

Please note that, it is not a good idea to return the address of a local variable outside the function as it goes out of scope after function returns. However, this feature is useful if the local variable is defined as static variable. A static variable do not goes out of scope even after function returns and preserves its values after each function call.

Example:

In the example below, a static variable is created inside the function and the function returns the address of that variable.

#include <stdio.h>

int * MyFunction() {
  static int count = 0;
  count++;
  return &count; 
}

int main () {
  int * p;
  for(int i = 1; i <= 3; i++) {
    p = MyFunction();
    printf("Function returns: %p\n", p); 
    printf("Value of count: %i\n", *p);    
  }
  return 0;
}

The output of the above code will be:

Function returns: 0x55b8f1202014
Value of count: 1
Function returns: 0x55b8f1202014
Value of count: 2
Function returns: 0x55b8f1202014
Value of count: 3

Example:

Consider one more example, where an array of 5 random variables is created inside a function and returns the address of first array element.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int * MyFunction() {
  static int rand_num[5];

  //initialize random seed
  srand (time(NULL));

  //generating 5 random number between 1 and 100
  for(int i = 0; i < 5; i++) {
    rand_num[i] = rand() % 100 + 1;
  }

  return rand_num;
}

int main () {
  int * p;
  
  p = MyFunction();
  for(int i = 0; i < 5; i++) {
    printf("(p + %i) = %p\n", i, (p+i)); 
    printf("*(p + %i) = %i\n", i, *(p+i));    
  }
  return 0;
}

The output of the above code will be:

(p + 0) = 0x563edd439020
*(p + 0) = 34
(p + 1) = 0x563edd439024
*(p + 1) = 9
(p + 2) = 0x563edd439028
*(p + 2) = 39
(p + 3) = 0x563edd43902c
*(p + 3) = 5
(p + 4) = 0x563edd439030
*(p + 4) = 23

❮ C - Pointers