Reversing Array by Returning Array from User Defined Function

Question: Write a Program in C that calls reversearray() to reverse the array and return the array and display the elements of reversed array using pointer.

Program


#include<stdio.h>
#include<conio.h>

/* Function Prototype
   Here return type is int * which means
   this function will return address and not value :)
*/
int *reverseArray(int n);

/* Main function */
int main()
{
 int *p, i, n;
 clrscr();
 printf("Enter number of elements in array:\n");
 scanf("%d", &n);
 p = reverseArray(n);
 /* Displaying output */
 printf("Reversed Array is:\n");
 for(i=0;i< n; i++)
 {
  printf("%d\t", *(p+i));
 }
 getch();
 return 0;
}
int* reverseArray(int n)
{
 /* C does not allow to return address of local
    variable outside of function that is why
    we are declaring array as static variable
 */
 static int a[20];
 int i, temp;
 /* Reading Array */
 printf("Enter array elements:\n");
 for(i=0;i< n;i++)
 {
  printf("a[%d]=",i);
  scanf("%d", &a[i]);
 }

 /* Reversing Array */
 for(i=0;i< n/2;i++)
 {
  temp = a[i];
  a[i] = a[n-1-i];
  a[n-1-i] = temp;
 }
 /*
 for(i=0;i< n;i++)
 {
  printf("%d\n",a[i]);
 } */
 /* Returning array (In this case address
    of first array element is returned
    and in main function which is received
    in pointer variable p. Pointer p in main
    function is referenced after returning from
    reverseArray() function.
 */
 return a;
}

Output of above program :

Enter number of elements in array:
5 ↲
Enter array elements:
a[0] = 1 ↲
a[1] = 2 ↲
a[2] = 3 ↲
a[3] = 4 ↲
a[4] = 5 ↲
Reversed array is:
5    4    3    2    1

Note: ↲ indicates ENTER is pressed.