[英]what does function “int (*function())[10];” mean?
我讀了一段代碼,發現有類似的功能。
int (*function())[10]{
...
}
我很迷惑。 這個功能意味着什么,它將返回什么?
它是一個函數的定義,它返回一個指向10個整數數組的指針。
請記住,返回值是指針 ,而不是實際數組。 無法從函數返回數組。 根據標准8.3.5 / 8的規定:
函數不應具有類型數組或函數的返回類型,盡管它們可能具有類型指針的返回類型或對此類事物的引用
這是一個如何使用它的簡單示例:
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
}
您可以在通常使用指針的地方使用它。 但請注意,除了指針之外還有更好的選擇,比如std::shared_ptr<std::array<T, N>>
或std::shared_ptr<std::vector<T>>
。
讀取它的方法是找到最左邊的標識符並解決問題,記住*
之前的那個()
和[]
綁定,所以*a[]
是一個指針數組, (*a)[]
是指向一個指針的指針array, *f()
是一個返回指針的函數, (*f)()
是一個指向函數的指針。 從而,
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.