You can pass an array to a function. Because a function can't tell how big the array is, you always pass the size as well:
#include <stdio.h>
int sum(int arr[], int size) {
int total = 0;
for (int i = 0; i < size; i++) {
total += arr[i];
}
return total;
}
int main() {
int a[3] = {1, 2, 3};
int b[5] = {10, 20, 30, 40, 50};
printf("%d\n", sum(a, 3));
printf("%d\n", sum(b, 5));
return 0;
}Output
6 150
Notice int arr[] has no number inside the brackets – it works for arrays of any size.
Functions can change an array
Normal variables are copied when you pass them (Module 6). Arrays are different: the function works on the original array. The usual way to write this is with a * (int *arr), which means the same as int arr[]. Module 9 explains why.
#include <stdio.h>
void doubleAll(int *arr, int size) {
for (int i = 0; i < size; i++) {
arr[i] = arr[i] * 2;
}
}
int main() {
int nums[4] = {1, 5, 7, 10};
doubleAll(nums, 4);
for (int i = 0; i < 4; i++) {
printf("%d ", nums[i]);
}
printf("\n");
return 0;
}Output
2 10 14 20
Remember: Pass an array together with its size. A function that changes the array changes the caller's array too.
Tip: In the challenges, write array parameters as
int *arr. The simple browser C runner handles that form best.