Codiqo

Learn C · lesson 36 of 60 · about 9 minutes

Project: Reverse in Place

Turn the past backups round to oldest first without making a copy, using two pointers that meet in the middle.

What you'll learn

  • Use two pointers from both ends
  • Swap through pointers
  • Reuse one function for any length

Oldest first

The past backups were typed newest first, but the report's last line lists them oldest first. Rather than copying them into a second array backwards, void reverse_ints(int *a, int n) turns the same array round: a left pointer starts at the first item and a right pointer at the last, they swap what they point to and move towards each other, and they stop when they meet. With no backups at all there's nothing to reverse, so the report says none instead.

Two pointers

To reverse in place:

1. Point left at the first item and right at the last
2. Swap what they point to
3. Move left forwards and right backwards
4. Stop when they meet

No second array is needed, so it works for any size.

Reversing ints and text

#include <stdio.h>
#include <string.h>

void reverse_ints(int *a, int n) {
    int *left = a;
    int *right = a + n - 1;
    while (left < right) {
        int temp = *left;
        *left = *right;
        *right = temp;
        left++;
        right--;
    }
}

void reverse_text(char *s) {
    char *left = s;
    char *right = s + strlen(s) - 1;
    while (left < right) {
        char temp = *left;
        *left++ = *right;
        *right-- = temp;
    }
}

int main(void) {
    int v[] = {1, 2, 3, 4, 5};
    reverse_ints(v, 5);
    for (int i = 0; i < 5; i++) printf("%d ", v[i]);
    printf("\n");

    char word[] = "stressed";
    reverse_text(word);
    printf("%s\n", word);
    return 0;
}

Output

5 4 3 2 1
desserts

Tip

*left++ = *right; copies, then moves left on. It's compact C, but split it over two lines whenever it makes things clearer.

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.