-1

I have a c++ struct which has a dynamically allocated array as a pointer. I have a function to reverse the array, but it doesn't seem to work (I think its because the temporary variable points to the original value).

struct s {

   int *array;
   int length;

   ...

   s(int n) {
       this->array = new int[n];
       this->length = n;
   }

   ...

   void reverse() {

       for (int i = 0; i < this->length; i++) {
           int n = this->array[i];
           this->array[i] = this->array[this->length - i - 1];
           this->array[this->length - i - 1] = n;
       }

   }

   ...

}

I think what this is doing is this->array[this->length - i - 1] = this->array[i] Hence the array remains the same and doesn't get reversed. I don't know how to deference the array pointer or how to just take the value of this->array[i] in n.

KSL
  • 1
  • 3
  • you logic does double reverse. For at i=0 you have put array[n-1] at array[0] , at i= n-1 you are putting array[0] at array[n-1]. – Mahesh Attarde Dec 11 '16 at 04:41
  • I think first part of for loop will make first half of array correct but then make "mirror" image of first half in second half. For code simplicity why not just make use of pointer array by reversing into second array then re-assighn pointer? – marshal craft Dec 11 '16 at 04:48
  • Recommend reading [What is the Rule of Three?](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) as it may stave off a few future questions. – user4581301 Dec 11 '16 at 04:51

2 Answers2

4

The reason your reverse doesn't work is that you're going through the length of the whole array. You need to only go through half of it. If you go through the second half, then you're un-reversing it.

As an example, if you try to reverse [1, 2, 3, 4] you get

after i = 0: [4, 2, 3, 1]
after i = 1: [4, 3, 2, 1]
--- reversed ---
after i = 2: [4, 2, 3, 1]
after i = 3: [1, 2, 3, 4]
--- back to original ---

Instead, just make your loop

for (int i = 0; i < this->length / 2; i++) {
    ...
}
Iluvatar
  • 1,537
  • 12
  • 13
0

On a side note, using 2 indexers will simplify your code considerably:

void reverse()
{
    int limit = length / 2;
    for ( int front = 0 , back = length - 1; front < limit; front++ , back-- )
    {
        int n = array[front];
        array[front] = array[back];
        array[back] = n;
    }

}
tinstaafl
  • 6,908
  • 2
  • 15
  • 22