Return pointer c – Returning Pointer from Function in C Programming

Return pointer c: In C programming, we can return a pointer from a function like any other data type.

Points to Remember
We should not return pointer to a local variable declared inside a function because as soon as control returns from a function all local variables gets destroyed. If we want to return pointer to a local variable then we should declare it as a static variable so that it retains it’s value after control returns from function.

Declaration of a Function Returning Pointer

int* getEvenNumbers(int N){
/* Function Body */
}

C Program Returning a Pointer from a Function

Returning Pointer from Function in C Programming

#include <stdio.h>
#include <conio.h>
  
/* This function returns an array of N even numbers */
int* getOddNumbers(int N){
    /* Declaration of a static local integer array */
    static int oddNumberArray[100];
    int i, even = 1;
      
    for(i=0; i<N; i++){
        oddNumberArray[i] = even;
        even += 2;
    }
    /* Returning base address of oddNumberArray array*/
    return oddNumberArray;
}
  
int main(){
   int *array, counter;
   array = getOddNumbers(10);
   printf("Odd Numbers\n");
    
   for(counter=0; counter<10; counter++){
       printf("%d\n", array[counter]);
   }
     
   getch();
   return 0;
}

Program Output

Odd Numbers
1
3
5
7
9
11
13
15
17
19