Return array in a function

后端 未结 19 2298
清酒与你
清酒与你 2020-11-22 05:23

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

int fillarr(int arr[])
{
    for(...);
    return arr;
         


        
19条回答
  •  孤独总比滥情好
    2020-11-22 06:04

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

提交回复
热议问题