Returning Array from Function

Since it is not possible to return the address of a local variable outside of a function it will need to be defined as a static variable, thus allowing a pointer (to that static variable) to be returned.

 

#include <stdio.h>

int *someFunction() //notice the pointer return type
{
	static int funcArray[5] = {17, 82, 63, 42, 50};

	for(int i = 0 ; i < 5 ; i++) //just to show this array exists
	{
		printf("Value in array element %d inside function is %d \n", i, funcArray[i]);
	}

	return funcArray ; //this is being returned as a pointer
}

int main ()
{
	int *pointer ; //declare the pointer to an int

	pointer = someFunction() ; //assign the returned pointer

	for( int i = 0; i < 5 ; i++ ) //now display the returned array
	{
		printf("Value in array element %d outside the function is: %d \n", i, *(pointer + i) );
	}

	return 0;
}

Leave a Reply