Example 1 — Sum and modify an array in place
The function edits the caller's array through the pointer.
#include <stdio.h>
int sum(const int a[], int n) {
int total = 0;
for (int i = 0; i < n; i++) total += a[i];
return total;
}
void double_all(int a[], int n) {
for (int i = 0; i < n; i++) a[i] *= 2;
}
int main(void) {
int v[] = {1, 2, 3, 4, 5};
printf("sum = %d\n", sum(v, 5));
double_all(v, 5);
for (int i = 0; i < 5; i++) printf("%d ", v[i]);
printf("\n");
return 0;
} How It Works
sumtakesconst int a[], so it cannot change the data.double_allmodifies the original elements.- The length
5travels as a separate argument.
