int (*x(int))[5]
says x is a function that takes an int
argument, and returns a pointer to an integer array of 5 elements.
I can also use typedef
to simplify x:
typedef int Array[5];
typedef Array *Array_ptr;
typedef Array_ptr Array_ptr_fn(int);
My question is, how do I use this type Array_ptr_fn?
// Define some_x to have type Array_ptr_fn,
Array_ptr_fn some_x;
// But then how do I use some_x since function cannot return array.
CodePudding user response:
The first thing to note is that x
is not a function pointer, but an actual function declaration. It's not a variable. A pointer to x
would have the type int (*(*ptr_to_x)(int))[5]
.
The second thing to note is that the return value of x
is neither int[5]
, nor int[]
, nor int*
, but int (*)[5]
. That is, you need to write (*retval)[0]
to get to an actual int
value.
With that in mind, it's not that hard to write a proof of concept that uses these types:
#include <stdio.h>
int arr[5] = { 11, 22, 33, 44, 55 };
int (*ptr)[5] = &arr;
int (*x(int ignored))[5]
{
return ptr;
}
int main(void)
{
int (*(*ptr_to_x)(int))[5] = &x;
int (*i)[5] = ptr_to_x(123);
printf("%d\n", (*i)[2]);
return 0;
}