在函数中返回数组 [英] Return array in a function
问题描述
我有一个数组 int arr[5]
传递给函数 fillarr(int arr[])
:
I have an array int arr[5]
that is passed to a function fillarr(int arr[])
:
int fillarr(int arr[])
{
for(...);
return arr;
}
- 如何返回该数组?
- 我将如何使用它,假设我返回了一个指针,我将如何访问它?
推荐答案
在这种情况下,您的数组变量 arr
实际上也可以被视为指向内存中数组块开头的指针,通过隐式转换.您正在使用的这种语法:
In this case, your array variable arr
can actually also be treated as a pointer to the beginning of your array's block in memory, by an implicit conversion. This syntax that you're using:
int fillarr(int arr[])
只是一种语法糖.你真的可以用这个替换它,它仍然可以工作:
Is kind of just syntactic sugar. You could really replace it with this and it would still work:
int fillarr(int* arr)
所以在同样的意义上,你想从你的函数中返回的实际上是一个指向数组中第一个元素的指针:
So in the same sense, what you want to return from your function is actually a pointer to the first element in the array:
int* fillarr(int arr[])
而且您仍然可以像使用普通数组一样使用它:
And you'll still be able to use it just like you would a normal array:
int main()
{
int y[10];
int *a = fillarr(y);
cout << a[0] << endl;
}
这篇关于在函数中返回数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!