Example 1 — Return a pointer to the maximum element
The caller can read or modify the element through the result.
#include <stdio.h>
int *find_max(int *a, int n) {
int *best = &a[0];
for (int i = 1; i < n; i++) {
if (a[i] > *best) best = &a[i];
}
return best;
}
int main(void) {
int data[] = {3, 9, 4};
int *m = find_max(data, 3);
printf("max = %d\n", *m);
*m = 0;
printf("%d %d %d\n", data[0], data[1], data[2]);
return 0;
} How It Works
find_maxreturns the address of the largest element.*m = 0edits the original array element.- The returned pointer is valid because
dataoutlives the call.
