Home > Programming > Functions using the "C" programming language > example16.c

 

Previous

Next


/*
    In this program we will see an example of a function that has returned value
    of type of pointer in an array. The function has a local variable of type of
    array declared with keyword "static", therefore the memory for this variable
    will be allocated at the beginning of program. With the definition variable
    as "static", we also achieve that the variable keeps its last value after
    successive calls of the function.
*/

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

#define SIZE 10

/*
    Function prototype.
    Function invert_nums returns a pointer to an array.
    It reverce the order of the array elements.
*/
int* invert_nums( int [] );

/*
    Function prototype.
    Function print_nums print the array elements.
*/
void print_nums( int [] );

void main()
{
    int array1[10] = { 0, 1, 2, 3, 4, 5 , 6, 7, 8, 9 };
    puts("Before inverting ... ");
/*
    We call the function print_nums to print the elements of array1 parameter
*/
    print_nums( array1 );
    puts("After inverting ... ");
/*
    We call the function print_nums passing as parameter the return value of
    the function invert_nums. Observe that as we have declred the function
    invert_nums it returns a pointer to an integer, but actually this is
    a way to return a pointer to an array of integers. A pointer to an array
    is the same as a pointer to the first element of the array.
*/
    print_nums( invert_nums( array1 ) );
    getch();
}

int* invert_nums( int nums[] )
{
/*
    We declare the local array variable using the keyword static, so the memory
    allocation will take place once, at the beginning of the program. After the
    function returns, the memory allocated by the array will not free.
*/
    static int array[SIZE];
    int i;
    for( i=0; i<SIZE; i++ )
    {
        array[i]=nums[SIZE-i-1];
    }
    return array;
}

void print_nums( int nums[] )
{
    int i;
    for( i=0; i<SIZE; printf("%d\n",nums[i++]) );
}


© 2004 Jim Valavanis

Previous

Next

1