![](/img/trans.png)
[英]int* const* foo(int x); is a valid C function prototype. How do you “read” this return type?
[英]How do you use this: int (*x(int))[5]
int (*x(int))[5]
說 x 是一個 function,它接受一個int
參數,並返回一個指向 integer 5 元素數組的指針。
我還可以使用typedef
來簡化 x:
typedef int Array[5];
typedef Array *Array_ptr;
typedef Array_ptr Array_ptr_fn(int);
我的問題是,如何使用這種類型的 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.
首先要注意的是x
不是 function指針,而是實際的 function 聲明。 它不是一個變量。 指向x
的指針的類型為int (*(*ptr_to_x)(int))[5]
。
第二點要注意的是x
的返回值既不是int[5]
也不是int[]
也不是int*
,而是int (*)[5]
。 也就是說,您需要編寫(*retval)[0]
以獲得實際的int
值。
考慮到這一點,編寫使用這些類型的概念證明並不難:
#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 */
您不能使用類型Array_ptr_fn
來定義變量...但是您可以使用指向該類型的指針來存儲將來調用的 function 引用(具有該接口),如:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.