Within the function pointer
the array A
is a local object of the function that will not be alive after exiting the function. The memory occupied by this array can be overwritten by other objects created in the program.
So returning pointer to a local object with the automatic storage duration of a function results in undefined behavior.
You could make the program valid the following way
#include <stdio.h>
int * pointer( int a[] )
{
a[0] = 1;
a[1] = 2;
return a;
}
#define N 10
int main(void)
{
int a[N];
int *p = pointer( a );
printf( "%d\n", *p );
printf( "%d\n", *( p + 1 ) );
return 0;
}
The program output is
1
2
Another approach is to declare a local array within the function but with the static storage duration.
For example
#include <stdio.h>
#define N 10
int * pointer( void )
{
static int a[N];
a[0] = 1;
a[1] = 2;
return a;
}
int main(void)
{
int *p = pointer();
printf( "%d\n", *p );
printf( "%d\n", *( p + 1 ) );
return 0;
}
In this case the array will be alive even after exiting the function.
Take into account that according to the C Standard the function main
without parameters shall be declared like
int main( void )
^^^^
also the function pointer
without parameters shall be also declared (when it is defined) like
int * pointer( void )
^^^^
{
//...
}