50. Reverse an Array Using Only Pointers

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>

void reverse_array(int *ptr, int n) {
   // 1. Set the 'start' pointer to the beginning of the array
    int *start = ptr;
    
    // 2. Set the 'end' pointer to the exact memory address of the last element
    // (ptr + n) points just OUTSIDE the array, so we subtract 1 to land on the last item.
    int *end = ptr + n - 1;

    // 3. Keep swapping as long as the start pointer is to the left of the end pointer
    while (start < end) {
        // Swap the values inside the memory addresses
        int temp = *start;
        *start = *end;
        *end = temp;

        // Move the pointers towards the center
        start++; // Move forward 1 integer (4 bytes)
        end--;   // Move backward 1 integer (4 bytes)
    }

// for(int i=0; i<n/2; i++)
// {
//     int temp = *(ptr + i);
//     *(ptr+i) = *(ptr + n - 1 - i);
//     *(ptr + n - 1 - i) = temp;
// }
}

int main() {
    int n;
    scanf("%d", &n);

    int arr[100];
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    reverse_array(arr, n);

    for (int i = 0; i < n; i++) {
        printf("%d", arr[i]);
        if(i < n-1){
            printf(" ");
        }
    }

    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote