In C, there are scenarios where you need to pass multiple values of the same type to a function. Rather than passing each value individually, you can pass an array, which simplifies the code and makes it more readable. This is particularly useful in functions that operate on a collection of values, such as sorting algorithms.
When passing an array to a function, you do not pass the actual array elements. Instead, you pass the reference to the array, which means the function can access and modify the actual array elements. The array name acts as a pointer to the first element of the array.
There are three common ways to declare a function that accepts an array as an argument:
return_type function(type arrayname[])
return_type function(type arrayname[SIZE])
return_type function(type *arrayname)
#include <stdio.h>
// Function declaration
void printArray(int arr[], int size);
int main() {
// Array declaration and initialization
int numbers[] = {1, 2, 3, 4, 5};
int size = sizeof(numbers) / sizeof(numbers[0]);
// Function call
printArray(numbers, size);
return 0;
}
// Function definition
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
1 2 3 4 5
#include <stdio.h>
// Function declaration
void modifyArray(int arr[], int size);
int main() {
// Array declaration and initialization
int numbers[] = {1, 2, 3, 4, 5};
int size = sizeof(numbers) / sizeof(numbers[0]);
// Function call
modifyArray(numbers, size);
// Print modified array
for (int i = 0; i < size; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
return 0;
}
// Function definition
void modifyArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
arr[i] *= 2; // Double each element
}
}
2 4 6 8 10