Reverse an array using pointers C++?

I am having trouble reversing my array in c++ using pointers. It reverses the first half of the array but then keeps going and the last two values are wrong; however, I don't understand why because my while loop should stop a duplication of the algorithm from happening. I can only use traversal by pointer, can't use another array, and can't use any other functions unless they are in std and iostream. Any suggestions? Thank you. 

// REQUIRES: there are at least n elements in arr;

// n >= 0

// MODIFIES: the elements in arr

// EFFECTS: Reverses the order of the elements in arr.

// EXAMPLE: If arr contains, [1,2,3,4,5], it would be modified to

// contain [5,4,3,2,1]

// NOTE: You must use traversal by pointer.

// You may not use an extra array.

//Expected output: 5 4 3 2 1

//Actual output: 5 4 3 4 5

void flip(int arr[], int n) {

    int *temp;

    int *ptr = arr;

    int *ptr_end = arr+n-1;


    while(ptr != ptr_end) {

        temp = ptr;

        *ptr = *ptr_end;

        *ptr_end = *temp;





3 Answers

  • 4 weeks ago

    I am currently busy, I will try and send this answer to you within this week. I like pointers a lot.

  • 4 weeks ago

    If you ran that with an even number of entries, you'd get an even more dramatic failure.

    There are two serious errors.

    First, your temp variable should be an int, not an int* pointer.  Swap *ptr with *ptr_end using:

        int temp = *ptr; // no need to have this outside the while loop

        *ptr = *ptr_end;

        *ptr_end = temp

    Your version with int *temp; and starting with temp = ptr just copies the pointer ptr.  It does not save the value in *ptr that's about to be overwritten.

    The second error is that if the array size is even, then ptr will never equal ptr_end and your while loop will keep reversing memory outside the array until your program crashes--usually with a segfault.  Change the loop condition to "while (ptr < ptr_end)" to fix that.

  • Snezzy
    Lv 7
    4 weeks ago

    Have you considered using two pointers--a source pointer and a destination pointer? Run one forwards and the other one backwards.


    husoski spent more time than I did, actually reading and understanding the code, rather than sending off a guess derived from a ten-second glance. Careful thinking can bring you success.

Still have questions? Get your answers by asking now.