在函数中返回数组 [英] Return array in a function

查看:23
本文介绍了在函数中返回数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组 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;
}

  1. 如何返回该数组?
  2. 我将如何使用它,假设我返回了一个指针,我将如何访问它?

推荐答案

在这种情况下,您的数组变量 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆