Return a pointer into an array, and use it to change that element.
What to build
A function that returns the address of an element.
Requirements
- Write
int *find_max(int *a, int n), returning a pointer to the first largest element. - Print
max V at I, using the pointer and pointer subtraction. - Set that element to 0 through the pointer, and print the whole array.
Input
The first line has n. The second line has n whole numbers.
Output
Two lines.
Constraints
n is from 1 to 100.
Example
Input:
4
3 9 2 7
Output:
max 9 at 1
3 0 2 7
Why it works
A returned pointer tells the caller where the value is, as well as what it is, so the caller can both find its index and change it.
Examples
Example 1 · Input
4 3 9 2 7
Expected output
max 9 at 1 3 0 2 7
Example 2 · Input
1 5
Expected output
max 5 at 0 0
Hints
Hint 1
Keep a pointer to the best element so far.
Hint 2
Subtracting two pointers into the same array gives the number of elements between them.
Hint 3
main can change the array through the pointer that is returned.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
int *find_max(int *a, int n) {
int *best = a;
for (int *p = a + 1; p < a + n; p++) {
if (*p > *best) {
best = p;
}
}
return best;
}
int main(void) {
int n, a[100];
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
int *p = find_max(a, n);
printf("max %d at %d\n", *p, (int)(p - a));
*p = 0;
for (int i = 0; i < n; i++) printf(i ? " %d" : "%d", a[i]);
printf("\n");
return 0;
}