Friday, July 29, 2016

C Basics - Returning Array from a Function in C

C allows a function to return a pointer to an array. A function returning pointer is defined as,

int * myFunction() {
   statement(s);
}

In order to return the address of a local variable to outside the function, you would have to define the local variable as static variable.


#include <stdio.h>

int *foo() {
    static int ret[10];
 int i;

    for( i = 0; i < 10; ++i) 
        ret[i] = i;

    return ret;
}
int main() {
    int *p = foo();
 int i;

 for ( i = 0; i < 10; i++ ) {
      printf( "*(p + %d) : %d\n", i, *(p + i));
    }
    return 0;
}
Output of above program,

*(p + 0) : 0
*(p + 1) : 1
*(p + 2) : 2
*(p + 3) : 3
*(p + 4) : 4
*(p + 5) : 5
*(p + 6) : 6
*(p + 7) : 7
*(p + 8) : 8
*(p + 9) : 9



Related topics:
Pointers in C   |   Pointer Arithmetic in C   |   Pointer to an Array in C   |   Array of Pointers in C   |   Pointer to Pointer in C   |   Pointers and Functions in C

List of topics: C Programming

No comments:

Post a Comment