简体   繁体   中英

How do you use this: int (*x(int))[5]

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.

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;
}
Array_ptr_fn some_x; /* ERROR */

You cannot use the type Array_ptr_fn to define a variable... but you can use a pointer to that type to store a function reference (with that interface) to be called in the future, as in:

int (*f1(int))[5];  /* implemented elsewhere */

Array_ptr_fn *some_function = f1;

int (*my_array)[5] = f1(27); 
 
/* or equivalently */

int (*my_second_array)[5] = some_function(27);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM