How to return an array from a function ?
How to return an array from a function in c: We can return a pointer to the base address(address of first element of array) of array from a function like any basic data type. However, C programming language does not allow to return whole array from a function.
We should not return base pointer of a local array declared inside a function because as soon as control returns from a function all local variables gets destroyed. If we want to return a local array then we should declare it as a static variable so that it retains it’s value after function call.
Declaration of a Function Returning Integer Array
int* getScoreList();
Returning an array from a function c++: Above function returns the base address of an integer array.
C Program to Return an Array from a Function
#include <stdio.h> #include <conio.h> /* This function returns an array of N even numbers */ int* getEvenNumbers(int N){ /* Declaration of a static local integer array */ static int evenNumberArray[100]; int i, even = 2; for(i=0; i<N; i++){ evenNumberArray[i] = even; even += 2; } /* Returning base address of evenNumberArray array*/ return evenNumberArray; } int main(){ int *array, counter; array = getEvenNumbers(10); printf("Even Numbers\n"); for(counter=0; counter<10; counter++){ printf("%d\n", array[counter]); } getch(); return 0; }
Program Output
Even Numbers 2 4 6 8 10 12 14 16 18 20