[英]what does function “int (*function())[10];” mean?
I read a piece of code and find there is a function like that. 我读了一段代码,发现有类似的功能。
int (*function())[10]{
...
}
I am confused. 我很迷惑。 What does this function mean and what will it return? 这个功能意味着什么,它将返回什么?
It is the definition of a function that returns a pointer to an array of 10 integers. 它是一个函数的定义,它返回一个指向10个整数数组的指针。
Remember that the return value is a pointer , not an actual array. 请记住,返回值是指针 ,而不是实际数组。 Arrays cannot be returned from functions. 无法从函数返回数组。 Per paragraph 8.3.5/8 of the Standard: 根据标准8.3.5 / 8的规定:
Functions shall not have a return type of type array or function, although they may have a return type of type pointer or reference to such things 函数不应具有类型数组或函数的返回类型,尽管它们可能具有类型指针的返回类型或对此类事物的引用
Here's a simple example of how you would use it: 这是一个如何使用它的简单示例:
int arr[10]; // an array of 10 int
int (*ptr)[10]; // pointer to an array of 10 int
int (*function())[10] // function returning a pointer to an array of 10 int
{
return ptr;
}
int main()
{
int (*p)[10] = function(); // assign to the pointer
}
You can use this wherever you would normally use a pointer. 您可以在通常使用指针的地方使用它。 But note that there are better alternatives than pointers altogether, like std::shared_ptr<std::array<T, N>>
or std::shared_ptr<std::vector<T>>
. 但请注意,除了指针之外还有更好的选择,比如std::shared_ptr<std::array<T, N>>
或std::shared_ptr<std::vector<T>>
。
The way to read it is to find the leftmost identifier and work your way out, remembering that ()
and []
bind before *
, so *a[]
is an array of pointers, (*a)[]
is a pointer to an array, *f()
is a function returning a pointer, and (*f)()
is a pointer to a function. 读取它的方法是找到最左边的标识符并解决问题,记住*
之前的那个()
和[]
绑定,所以*a[]
是一个指针数组, (*a)[]
是指向一个指针的指针array, *f()
是一个返回指针的函数, (*f)()
是一个指向函数的指针。 Thus, 从而,
function - function
function() - is a function
*function() - returning a pointer
(*function())[10] - to a 10-element array
int (*function())[10] - of int
这意味着它是一个函数指针,参数为void并返回int [10]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.