Arrays as function arguments
In C programming, arrays can be passed as function arguments. When an array is passed to a function, it is actually passed by reference, which means the function receives a pointer to the array.
Here's an example of passing an array to a function in C:
#include <stdio.h>
// Function that takes an array as an argument
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int size = sizeof(numbers) / sizeof(numbers[0]);
// Calling the function and passing the array
printArray(numbers, size);
return 0;
}
Output:
1 2 3 4 5
In this example, we have a function `printArray()` that takes two arguments: an integer array `arr[]` and its size `size`. Inside the function, we loop through the elements of the array and print them.
In the `main()` function, we declare an array `numbers` and calculate its size by dividing the total size of the array by the size of one element. Then, we call the `printArray()` function, passing the `numbers` array and its size as arguments.
When the array is passed as an argument, it is actually passed as a pointer to the first element of the array. So any changes made to the array inside the function will affect the original array in the `main()` function.