Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...