gpt4 book ai didi

c++ - 函数 "int (*function())[10];"是什么意思?

转载 作者:IT老高 更新时间:2023-10-28 21:41:30 24 4
gpt4 key购买 nike

我看了一段代码,发现有这样的函数。

int (*function())[10]{
...
}

我很困惑。这个函数是什么意思,它会返回什么?

最佳答案

它是一个函数的定义,它返回一个指向 10 个整数数组的指针。

请记住,返回值是一个指针,而不是一个实际的数组。数组不能从函数返回。根据标准第 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

这里有一个简单的例子来说明你将如何使用它:

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>> .

关于c++ - 函数 "int (*function())[10];"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17012648/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com