Don't do this.
You are returning a pointer to a local variable. When the function returns, that pointer points to a location that's no longer valid, so this exercise is pointless.
The return type would have been int (*)[3]
though, but when you use that as a return type of a function, the prototype would be int (*fun(void))[3]
(ugh, eew)
However
If a
was static, you could do
int (*fun(void))[3]
{
static int a[3]={3,3,4};
return &a;
}
It's more common to return a pointer to the first element in an array - though you'll have to "know" in the caller that you can access 3 and only 3 elements of that pointer.
int *fun(void)
{
static int a[3]={3,3,4};
return &a[0]; // or just return a;
}
Since a
is static in these cases, you'll have to worry about reentrancy
2 more common ways of achieving the same:
Pass in the array through the parameters and allocate it in the caller:
void fun(int *a)
{
a[0] = 3;
a[1] = 3;
a[2] = 4;
}
Call it like:
int a[3];
fun(a);
Dynamically allocate the memory:
int *fun(void)
{
int *a = malloc(3*sizeof *a);
if(a) {
a[0] = 3;
a[1] = 3;
a[2] = 4;
}
return a;
}
Call it like:
int *a;
a = fun();
if(a) {
///use a
free(a); // remember to free it when done
} else {
//out of memory
}