Pointer Assignment 4 — Reverse an Array Using Pointers
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Reverse an Array Using Pointers — The Two-Pointer Swap

📑 On this page:
  • The Two-Pointer Idea
  • How the Pointers Move
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to position one pointer at the start and another at the end of an array
  • How to swap values through those pointers and then move them inward
  • Why the loop condition left < right (not <=) is correct
  • How to reverse in place without using extra memory for a copy
  • How to return a different pointer (the new logical start) if you want an out-of-place variation

The Two-Pointer Idea

Reversing an array means the first element becomes the last, the second becomes the second-to-last, and so on. The most efficient way to do this is with two pointers: one pointing at the first element, one pointing at the last. Swap the values behind them, then step them toward each other — left++ and right--. Repeat until they meet or cross. Every element ends up exactly where it belongs, and the array is reversed in place.

This is a beautiful first application of pointers because it makes the "address arithmetic" point very concrete. The two pointers are literally moving through memory, and the loop terminates when their addresses collide. Nothing in the algorithm needs indices — the pointers are the positions.

Doing this with indices is fine too, but the pointer version generalizes cleanly. If later you're reversing a linked list, or reversing a subrange of a string, or reversing only the middle of an array, the same two-pointer pattern carries over almost word-for-word. That's why it's worth learning here.

💡 In one line: Two pointers, one at each end. Swap through them, move them inward, repeat until they meet. That's it.

Diagram of an array being reversed in place with two pointers left and right, swapping elements and moving inward

How the Pointers Move

Step Initial array left → ← right Action
Start10, 20, 30, 40, 501050Swap 10 ↔ 50
After swap 150, 20, 30, 40, 102040Swap 20 ↔ 40
After swap 250, 40, 30, 20, 103030Pointers meet — stop
Done50, 40, 30, 20, 10——Array reversed

Two things to notice. First, the loop runs only n / 2 times — half the array length, because each swap fixes two positions at once. That's why reversal is O(n) but with a very small constant. Second, the loop condition must be left < right, not left <= right. When left == right, both pointers point at the same element — the middle one in an odd-length array — and swapping it with itself is a harmless but pointless no-op. Using < stops one step earlier and skips the pointless operation. In an even-length array, the pointers will cross without ever being equal, so either condition would work — but < is correct in both cases.

Complete C Program

Program: reverse an array in place using two pointers

#include <stdio.h>

/* Reverse n ints starting at *arr, in place. */
void reverse_array(int *arr, int n) {
    if (arr == NULL || n <= 1) {
        return;                 /* nothing to do */
    }

    int *left  = arr;           /* points at arr[0] */
    int *right = arr + n - 1;   /* points at arr[n-1] */

    while (left < right) {
        /* swap *left and *right through their pointers */
        int temp = *left;
        *left  = *right;
        *right = temp;

        left++;                 /* step toward the center */
        right--;
    }
}

/* Small helper to print an array */
void print_array(const int *arr, int n) {
    for (int i = 0; i < n; i++) {
        printf("%d", *(arr + i));
        if (i < n - 1) printf(", ");
    }
    printf("\n");
}

int main(void) {
    int arr[6] = {10, 20, 30, 40, 50, 60};
    int n = 6;

    printf("Before reverse: ");
    print_array(arr, n);

    reverse_array(arr, n);

    printf("After reverse : ");
    print_array(arr, n);

    /* Try an odd-length array to exercise the middle-element case */
    int odd[5] = {1, 2, 3, 4, 5};
    printf("\nBefore reverse: ");
    print_array(odd, 5);
    reverse_array(odd, 5);
    printf("After reverse : ");
    print_array(odd, 5);

    return 0;
}
                                    

Program Output

Before reverse: 10, 20, 30, 40, 50, 60
After reverse : 60, 50, 40, 30, 20, 10

Before reverse: 1, 2, 3, 4, 5
After reverse : 5, 4, 3, 2, 1
                                

Both arrays are reversed in place — the even-length one swaps six elements down to zero, and the odd-length one swaps the outer pairs and leaves the middle element (3) exactly where it belongs. The middle element never gets touched, which is the correct behaviour: it's already in the reversed position by symmetry.

Step-by-Step Explanation

Let's trace the six-element array through the loop, then look at why the odd-length case works.

1. Setup — left = arr; right = arr + 5;

left points at arr[0] (value 10). right points at arr[5] (value 60). The two pointers bracket the entire array. The expression arr + 5 walks five ints past the start — five times the size of an int in bytes — landing exactly on the last element.

2. First iteration — swap 10 ↔ 60

temp = *left saves 10. *left = *right writes 60 into arr[0]. *right = temp writes 10 into arr[5]. The array now reads 60, 20, 30, 40, 50, 10. Then left++ moves left to arr[1] and right-- moves right to arr[4].

3. Second iteration — swap 20 ↔ 50

Same swap logic. arr[1] becomes 50, arr[4] becomes 20. Array is 60, 50, 30, 40, 20, 10. Pointers advance: left → arr[2], right → arr[3].

4. Third iteration — swap 30 ↔ 40

arr[2] becomes 40, arr[3] becomes 30. Array is 60, 50, 40, 30, 20, 10. Pointers advance: left → arr[3], right → arr[2]. Now left > right, so the loop condition left < right is false. Loop exits. Reversal complete.

5. The odd-length case — 5 elements

left starts at arr[0], right at arr[4]. Swap 1 ↔ 5, advance. Now left at arr[1], right at arr[3]. Swap 2 ↔ 4, advance. Now left and right both point at arr[2] (value 3). Because the condition is left < right, and left == right, the loop exits. The middle element is never touched. That's exactly what we want — it's the pivot.

6. Why < and not <=?

If we wrote while (left <= right), the odd-length array would swap the middle element with itself in the final iteration. That's a no-op for the data — 3 gets written to temp, then arr[2] = arr[2] writes 3 back, then arr[2] = 3 writes it again. No harm, but no purpose. Worse, if the array had been of length 1, we'd still go through that pointless cycle. left < right avoids it entirely.

7. In place vs out of place

This algorithm reverses the array in place — it modifies the original array and doesn't require extra memory. That's why it runs in O(1) auxiliary space. An alternative is to allocate a second array of the same size and copy elements from arr[n-1-i] into rev[i]. That's O(n) extra memory but easier to reason about if you need to preserve the original. For most practical work the in-place version is preferred.

8. Why pass a pointer and a length?

The function receives int *arr and int n. Inside the function, arr is just a pointer to the first element — it carries no information about how many elements exist. That's why n must be passed separately. Forgetting this is the most common source of array bugs in C. The alternative is to terminate arrays with a sentinel (like '\0' in strings), which only works for character arrays. For ints, always pass the length.

9. The NULL / n <= 1 guard

If someone passes n = 0 or n = 1, the array is already "reversed" trivially. The guard returns immediately to avoid computing arr + n - 1, which would be arr - 1 for n = 0 — a pointer before the start of the array, which is undefined behaviour. If n > 0 is guaranteed by the caller, the guard still helps if someone accidentally passes NULL. Two cheap checks; much better sleep.

10. Reversing subranges — the general pattern

The two-pointer swap technique works for any subrange. If you want to reverse only arr[i] through arr[j], set left = arr + i and right = arr + j and run the same loop. This is exactly how you'd reverse a portion of an array without copying. For example, a classic interview problem asks you to rotate an array by k positions — the standard O(1)-space solution is three calls to reverse_range. The pattern generalizes because the algorithm only knows two pointers, not indices.

🎯 Remember this: Two-pointer reversal is symmetric by design — every swap fixes two positions. When the pointers cross, everything is where it belongs. If you're ever tempted to use <=, remember that it just performs one extra no-op swap on odd-length arrays.

Frequently Asked Questions

1. Can I reverse the array in place without a temp variable?

Yes, with the XOR swap trick: *left ^= *right; *right ^= *left; *left ^= *right;. It avoids the temp variable syntactically. But it has two problems. First, it fails if left and right point to the same address — the XOR would zero out the element. Second, it's much harder to read and provides no real optimization (the compiler generates the same code either way). Use the temp variable; it's clearer and safer.

2. Does this work for an array of strings or structs?

Yes, but with a caveat. For arrays of structs, the swap must be a proper struct swap — either struct foo temp = *left; *left = *right; *right = temp; (a complete struct copy), or a byte-wise copy with memcpy. For arrays of strings (which are char * in C, or char [N] in strings), the swap exchanges the pointers or character blocks. The two-pointer loop itself is unchanged — it's the type of the pointer and the swap operation that vary.

3. Why not just use for (int i = 0; i < n/2; i++)?

That works too. The pointer version is arguably more elegant because the loop's invariants are clearer — left and right literally mark the boundary of what remains to be swapped. If you refactor to reverse a subrange or a linked list, the pointer version transfers more directly. But for a simple in-place reversal, both are fine. Choose whichever reads better for you.

4. What if the array is empty?

Nothing happens. With n = 0, the guard if (n <= 1) return; catches it before we touch the pointers. If you removed the guard, arr + n - 1 would be arr - 1 — a pointer before the start of the array, which is undefined behaviour. Always have that guard for safety.

5. Can I return the reversed array?

Not as a new value — the array's contents are modified in place. If you want to return a pointer, you'd return arr itself (which is unchanged — it still points to the same memory, now containing reversed values). If you want two arrays (original plus reversed copy), you'd need to allocate a new array and copy into it. That's a different algorithm (O(n) extra memory).

6. Is reverse_array O(1) space?

Yes. The function uses only a handful of local variables (left, right, temp) regardless of how large the array is. That's O(1) auxiliary space — constant. The time complexity is O(n) because we do one swap per pair of elements, and there are n/2 pairs. Both are optimal for reversal: you can't reverse an array in fewer than O(n) swaps, and you can't do it without visiting each element.

💡 Tip: Once this works, try reversing only part of the array. Write a reverse_range(int *arr, int lo, int hi) that reverses elements from index lo to hi inclusive. Then use it to solve the "rotate array by k positions" problem in O(1) space: reverse the whole array, then reverse the first k elements, then reverse the last n-k elements. It's one of the most elegant applications of this technique.

📖 Related Tutorials

  • 3. Sum of Array Elements Using Pointers
  • 5. Length of a String Using Pointers
  • 19. Reverse a String Using Pointers
  • 15. Swap Two Elements in an Array Using Pointers
  • 18. Sort an Array Using Pointers
  • The Pointer To An Array
  • All 30 Pointer Assignments

Previous Topic: -->> 3. Sum of Array Elements Using Pointers   ||   Next Topic: -->> 5. Length of a String Using Pointers


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.