Returning Arrays in Functions
In C , arrays are not first-class objects, which means that they cannot be directly returned from functions. However, there are two common approaches to working with arrays in functions:
Approach 1: Passing by Reference
As demonstrated in the question, an array can be passed to a function as a reference, allowing the function to modify the original array. The function can then return a void or another data type while still having access to the updated array.
Approach 2: Returning a Pointer
Alternatively, arrays can be returned from functions as pointers to their first element. This is essentially the same as passing by reference, as the function can still access and modify the original array through the pointer.
Implementation Example:
int* fillArray(int arr[], int size) { for (int i = 0; i < size; ++i) { arr[i] = i + 1; } return arr; } int main() { int arr[5]; int* result = fillArray(arr, 5); // Access and print the modified array through the pointer for (int i = 0; i < 5; ++i) { cout << result[i] << " "; } cout << endl; return 0; }
In this example, the fillArray function takes an array reference and a size as input and returns a pointer to the first element of the modified array. The main function calls this function and stores the result in a pointer. It then accesses the modified array through this pointer.
The above is the detailed content of How Can I Return and Modify Arrays in C Functions?. For more information, please follow other related articles on the PHP Chinese website!