C/C++ Arena

Step 9 of 10

Two pointers from both ends

A very common pattern: one pointer starts at the front, one at the back, and they walk toward each other until they meet.

int *lo = a, *hi = a + n - 1;
while (lo < hi) {
    /* work with *lo and *hi */
    lo++;
    hi--;
}

Comparing two pointers with < is fine when both point into the same array.

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