Example 1 — Fill an array and find its maximum
One function writes squares; another reads them.
#include <stdio.h>
void fill_squares(int out[], int n) {
for (int i = 0; i < n; i++) out[i] = (i + 1) * (i + 1);
}
int max_of(const int a[], int n) {
int m = a[0];
for (int i = 1; i < n; i++) if (a[i] > m) m = a[i];
return m;
}
int main(void) {
int v[5];
fill_squares(v, 5);
printf("squares:");
for (int i = 0; i < 5; i++) printf(" %d", v[i]);
printf("\nmax: %d\n", max_of(v, 5));
return 0;
} How It Works
fill_squareswrites into the caller's array.max_oftakesconst int a[]because it only reads.- Both functions receive the length
5as an argument.
