Returning an Array in a Function
In C , it's often necessary to return arrays from functions. The question below explores this topic:
Question:
Consider an array int arr[5] passed to the function fillarr(int arr[]).:
int fillarr(int arr[]) { for(...); return arr; }
a) How can we return the array?
b) If we return a pointer, how do we access it?
Answer:
a) The array variable arr can be treated as a pointer to the beginning of its memory block. The following syntax:
int fillarr(int arr[])
is equivalent to:
int fillarr(int* arr)
Therefore, we can return a pointer to the first array element:
int* fillarr(int arr[])
b) To access the returned pointer, we can use it like a normal array in the calling function:
int y[10]; int *a = fillarr(y); cout << a[0] << endl;
The above is the detailed content of How Can I Return and Access an Array from a C Function?. For more information, please follow other related articles on the PHP Chinese website!