C - Passing 1D Arrays to Functions
In C, you can pass one-dimensional arrays to functions. When you pass an array to a function, you are essentially passing a pointer to the first element of the array. Here's an example of how to pass a one-dimensional array to a function:
Example:
#include <stdio.h>
// Function to print the elements of an integer array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int myArray[] = {1, 2, 3, 4, 5};
int size = sizeof(myArray) / sizeof(myArray[0]);
printf("Original array: ");
printArray(myArray, size); // Passing the array to the function
// You can also modify the elements of the array inside the function
for (int i = 0; i < size; i++) {
myArray[i] *= 2;
}
printf("Modified array: ");
printArray(myArray, size);
return 0;
}
In this example:
- The
printArray
function takes two parameters: an integer array (arr
) and its size (size
).
- Inside the
main
function, an integer array myArray
is defined, and its size is determined using the sizeof
operator.
- The
printArray
function is called twice, once to print the original array and once after modifying the array elements inside the main
function.
Output:
Original array: 1 2 3 4 5
Modified array: 2 4 6 8 10
When you pass an array to a function, you can read and modify the array's elements within the function. However, it's important to note that the array's size is not explicitly passed to the function. Therefore, it's crucial to pass the size of the array as a separate parameter, as shown in the example.
Additionally, keep in mind that C does not allow you to return an entire array from a function directly. If you need to create or modify an array within a function and return it, you can do so by dynamically allocating memory for the array and returning a pointer to the allocated memory, as discussed in a previous response.