Step 9 of 10
Two pointers from both ends
The two-pointer technique comes up constantly, in interviews and in real code. One pointer starts at the front, another at the back, and they move toward each other, doing some work at each step, until they meet.
#include <stdio.h>
int is_mirror(const int *a, int n) {
const int *lo = a;
const int *hi = a + n - 1;
while (lo < hi) {
if (*lo != *hi) {
return 0;
}
lo++;
hi--;
}
return 1;
}
int main(void) {
int x[] = {1, 4, 9, 4, 1};
int y[] = {1, 2, 3};
printf("%d %d\n", is_mirror(x, 5), is_mirror(y, 3));
return 0;
}
1 0
The details that matter
a + n - 1points at the last element.a + nwould be one past the end.lo < hicompares positions. Comparing pointers with<is valid when both point into the same array. The loop stops when they meet (odd length, middle element) or cross (even length).- Each pass moves
loforward andhibackward, so the loop always finishes.
The example checks whether the array reads the same from both ends. Reversing uses the same walk, but instead of comparing, it swaps the two values the pointers point at. You already know how to swap through pointers from step 2.
Try it on paper with 4 and 5 elements before coding, to see exactly which pairs get touched.
Your turn: write void reverse(int *a, int n) that reverses the array in place using two pointers (no [ ]).
Previous: const and pointers Next: Challenge: squeeze out spaces