Ismail Marmoush Ismail Marmoush - 15 days ago 4x
C++ Question

Return array in a function

I have an array

int arr[5]
that is passed to a function
fillarr(int arr[])

int fillarr(int arr[])
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?


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;