patterncppCritical
Return array in a function
Viewed 0 times
functionarrayreturn
Problem
I have an array
int arr[5] that is passed to a function fillarr(int arr[]):int fillarr(int arr[])
{
for(...);
return arr;
}- How can I return that array?
- How will I use it, say I returned a pointer how am I going to access it?
Solution
In this case, your array variable
Is kind of just syntactic sugar. You could really replace it with this and it would still work:
So in the same sense, what you want to return from your function is actually a pointer to the first element in the array:
And you'll still be able to use it just like you would a normal array:
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;
}Code Snippets
int fillarr(int arr[])int fillarr(int* arr)int* fillarr(int arr[])int main()
{
int y[10];
int *a = fillarr(y);
cout << a[0] << endl;
}Context
Stack Overflow Q#3473438, score: 258
Revisions (0)
No revisions yet.