Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

c++ - 在函数中返回数组(Return array in a function)

I have an array int arr[5] that is passed to a function fillarr(int arr[]) :

(我有一个数组int arr[5]传递给函数fillarr(int arr[]) :)

int fillarr(int arr[])
{
    for(...);
    return arr;
}
  1. How can I return that array?

    (如何返回该数组?)

  2. How will I use it, say I returned a pointer how am I going to access it?

    (我将如何使用它,说我返回了一个指针,我将如何访问它?)

  ask by Ismail Marmoush translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

(在这种情况下,通过隐式转换,您实际上也可以将数组变量arr视为指向数组在内存中块的开头的指针。)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...